android在发送到服务器之前压缩图像大小

时间:2016-10-17 13:12:52

标签: android image-compression

我尝试过互联网上的多种解决方案但没有运气,当我在应用上传时,如何更改图像尺寸? 我希望它能够在我上传2MB文件时将其发送到size = 50kb的服务器。 请帮帮我

@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;
}

2 个答案:

答案 0 :(得分:0)

尝试在下面使用它会将图像压缩到80%。您可以根据需要更改压缩百分比。

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;
}

答案 1 :(得分:0)

尝试

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 ();
}