package cn.flightfeather.thirdappmodule.task; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import cn.flightfeather.thirdappmodule.activity.UploadMediaFilesActivity; import cn.flightfeather.thirdappmodule.bean.entity.Mediafile; import cn.flightfeather.thirdappmodule.util.photo.OnCompressListener; /** * Created by note_ff_1602 on 2018/1/27. * 压缩图片的task */ public class CompressPhotoTask extends AsyncTask{ List mediafileList; String path = "FlightFeather/Temp/"; private UploadMediaFilesActivity activity; private List outputFIleList; private OnCompressListener onCompressListener; public CompressPhotoTask(List mediafileList, UploadMediaFilesActivity activity) { this.mediafileList = mediafileList; this.activity = activity; } public CompressPhotoTask(List mediafileList, OnCompressListener onCompressListener) { this.mediafileList = mediafileList; this.onCompressListener = onCompressListener; } @Override protected Object doInBackground(Object[] objects) { outputFIleList = new ArrayList<>(); for (Mediafile mediafile:mediafileList){ File file = new File(Environment.getExternalStorageDirectory(),(mediafile.getPath()+mediafile.getDescription())); String fileName = mediafile.getGuid()+".jpg"; File outputFile = new File(Environment.getExternalStorageDirectory(),path+fileName); outputFile.getParentFile().mkdirs(); BitmapFactory.Options opts = new BitmapFactory.Options(); //将图片的长宽缩小为1/2 opts.inSampleSize = 2; Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath(), opts); int aa = bm.getHeight(); int bb = bm.getWidth(); Log.i("bitmap", bm.getHeight() + " " + bm.getWidth()); //压缩缩略图 Bitmap bmSmall = null; int normalSize = 1440; int width, height = 0; if (bm.getWidth() >= bm.getHeight()) { width = normalSize; height = normalSize * bm.getHeight() / bm.getWidth(); } else { height = normalSize; width = normalSize * bm.getWidth() / bm.getHeight(); } if (bm != null) { bmSmall = Bitmap.createScaledBitmap(bm, width, height, true); try { // 当图片大于1MB时,才会进行压缩处理 if (file.length() > 1024L * 1024) { bmSmall.compress(Bitmap.CompressFormat.JPEG, 80, new FileOutputStream(outputFile.getAbsolutePath())); } else { bmSmall.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(outputFile.getAbsolutePath())); } Log.i("compress success", outputFile.getAbsolutePath()); outputFIleList.add(outputFile); bm.recycle(); bmSmall.recycle(); } catch (FileNotFoundException e) { e.printStackTrace(); Log.i("compress failure", outputFile.getAbsolutePath()); } } } return outputFIleList; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); if (activity != null){ activity.startUplaod(outputFIleList); } if (onCompressListener != null) { onCompressListener.onCompressed(outputFIleList); } } }