package com.future.driver.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class BitmapUtil { public static String bitmap2File(Context context, Bitmap bitmap, String name) { File file = new File(context.getExternalCacheDir() + "/image/"); if (!file.exists()) { file.mkdirs(); } File f = new File(file, name + ".jpg"); FileOutputStream fOut = null; try { fOut = new FileOutputStream(f); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); fOut.flush(); fOut.close(); } catch (IOException e) { return ""; } return f.getAbsolutePath(); } /** * 图片按比例大小压缩方法 * * @param srcPath (根据路径获取图片并压缩) * @return */ public static Bitmap getimage(String srcPath, float width, float height) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 newOpts.inJustDecodeBounds = true; // 此时返回bm为空 Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为 // 这里设置高度为800f float hh = height; // 这里设置宽度为480f float ww = width; // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 // be=1表示不缩放 int be = 1; // 如果宽度大的话根据宽度固定大小缩放 if (w > h && w > ww) { be = (int) (newOpts.outWidth / ww); // 如果高度高的话根据宽度固定大小缩放 } else if (w < h && h > hh) { be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; // 设置缩放比例 newOpts.inSampleSize = be; // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 bitmap = BitmapFactory.decodeFile(srcPath, newOpts); // 压缩好比例大小后再进行质量压缩 // return compressImage(bitmap); //不进行质量压缩 return bitmap; } public static String getShareIconPath(Context context, int resourse) { File file = new File(context.getExternalCacheDir() + "/image/share_icon.jpg"); if (file.exists()) { return file.getAbsolutePath(); } //保存图片 Bitmap thumbBmp = BitmapFactory.decodeResource(context.getResources(),resourse); String share_icon = bitmap2File(context,thumbBmp, "share_icon"); return share_icon; } }