[英]android compress image size before sending to server
I have tried multiple solutions from the internet with no luck, How do I go about changing the image size when I upload on app?我已经尝试了互联网上的多种解决方案,但都没有成功,当我上传到应用程序时,如何更改图像大小? I want it to be in a way that when I upload a 2MB file,it gets sent to the server with size = 50kb.我希望它的方式是,当我上传 2MB 文件时,它会以大小 = 50kb 的方式发送到服务器。 Please help me请帮帮我
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//get image thumbnail
if (requestCode == REQUEST_CODE_PICKER && resultCode == RESULT_OK && data != null) {
ArrayList<Image> images = data.getParcelableArrayListExtra(ImagePickerActivity.INTENT_EXTRA_SELECTED_IMAGES);
absolutePath = null;
// do your logic ....
for (Image img : images) {
Log.v(LOG_TAG, img.getName() + " " + img.getPath());
absolutePath = img.getPath();
absolutePath = String.valueOf(Compressor.getDefault(getContext()).compressToFile(imageFile));
Bundle bundleExtras = data.getExtras();
image = (Bitmap) bundleExtras.get("data");
}
consultantProfileImageView.setImageBitmap(getBitmapFromPath(absolutePath));
new UploadConsultantProfileImageTask(getContext(), absolutePath).execute();
postConsultant();
}
}
public File getBitmapFromPath(String filePath) {
File imageFile = new File(filePath);
Bitmap imageBitmap = null;
imageBitmap = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream in = new ByteArrayInputStream(bos.toByteArray());
File compressedImageFile = Compressor.getDefault(getContext()).compressToFile(imageFile);
if (compressedImageFile.exists()) {
imageBitmap = BitmapFactory.decodeFile(compressedImageFile.getAbsolutePath());
}
return compressedImageFile;
}
Try using below it will compress the image to 80 percent.尝试在下面使用它会将图像压缩到 80%。 You can change the percentage of compression according to your requirement.您可以根据需要更改压缩百分比。
public File getBitmapFromPath(String filePath) {
File imageFile = new File(filePath);
OutputStream fout = new FileOutputStream(file);
Bitmap bitmap= BitmapFactory.decodeFile(filePath);
bitmap.compress(CompressFormat.JPEG, 80, fout);
fout.flush();
fout.close();
return imageFile;
}
Try试试
int compressionRatio = 2; //1 == originalImage, 2 = 50% compression, 4=25% compress
File file = new File (imageUrl);
try {
Bitmap bitmap = BitmapFactory.decodeFile (file.getPath ());
bitmap.compress (Bitmap.CompressFormat.JPEG, compressionRatio, new FileOutputStream (file));
}
catch (Throwable t) {
Log.e("ERROR", "Error compressing file." + t.toString ());
t.printStackTrace ();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.