多张照片压缩

时间:2014-12-23 09:19:02

标签: android android-asynctask photo image-compression

我需要减少照片尺寸,而照片尺寸不低于1MB。那我怎么做我有活动,我可以拍摄照片,然后在活动结果我开始AsyncTask,压缩我的照片。压缩效果很好,照片保存好如果只进行一次压缩,但是如果我尝试多次照片压缩,我会得到无限循环,有趣的照片尺寸在每次压缩后都会增加,但为什么呢?谁知道我做得不好?我找到了一些更改照片分辨率的样本,但我不想更改照片分辨率,我只想应用多张照片压缩。

    public class PhotoSaverAsyncTask extends AsyncTask<Void, Void, Void> {
    private int compressionLevel = 99; //if not set then default 99
    private Bitmap bitmap = null;
    private final int MAX_PHOTO_SIZE_IN_KILO_BYTES = 1024; // 1MB
    private PhotoSavedNotify photoSavedNotify = null;
    private ProgressDialog mProgressDialog = null;

    public PhotoSaverAsyncTask(int compressionLevel, PhotoSavedNotify photoSavedNotify) {
        super();
        this.compressionLevel = compressionLevel;
        this.photoSavedNotify = photoSavedNotify;
    }

    protected void onPreExecute() {
        mProgressDialog = new ProgressDialog(activity);
        mProgressDialog.setTitle("Kompresia fotografie...");
        mProgressDialog.setMessage("Čakajťe prosím...");
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.show();
    }

    protected Void doInBackground(Void... params) {
        try {
            Log.d(this.toString(), "Original size: " + (getMediaFile().length() / 1024) + "Kb");
            compressionMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(Void unused) {
        mProgressDialog.dismiss();
        if ((getMediaFile().length() / 1024) > MAX_PHOTO_SIZE_IN_KILO_BYTES) //1MB
        {
            new PhotoSaverAsyncTask(compressionLevel, photoSavedNotify).execute(); 
            //compressionMethod(); I also try while cycle without start another tak but the same result
        } else {
            photoSavedNotify.taskCompletionResult(getMediaFileName());
        }
    }

    private void compressionMethod() {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            bitmap = BitmapFactory.decodeFile(getMediaFileUri().getPath(), options);
            FileOutputStream out = new FileOutputStream(getMediaFile());
            bitmap.compress(Bitmap.CompressFormat.JPEG, compressionLevel, out);
            out.flush();
            out.close();
            Log.d(this.toString(), "After compression size: " + (getMediaFile().length() / 1024) + "Kb");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2 个答案:

答案 0 :(得分:3)

如果在压缩后尺寸仍然太大,则不应压缩压缩的照片。相反,您应该使用不同的compressionLevel值压缩原始照片。

如果您压缩压缩的照片,它可能会变得更大,因为前一轮压缩的压缩效果与未压缩的照片没有相同的平滑过渡。

答案 1 :(得分:0)

多次压缩是没用的。对于给定的分辨率和质量,只有这么多。如果不改变这些参数,就不可能获得更小的尺寸。