Android 压缩图片到指定尺寸 并压缩
压缩到指定尺寸:
public static Bitmap small(Bitmap bitmap) {
Bitmap resizeBmp = null;
//设置长宽压缩比例进行压缩
//Matrix matrix = new Matrix();
//matrix.postScale(0.36f,0.36f); //长和宽放大缩小的比例
//Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
//压缩到指定尺寸
if (bitmap.getHeight() > bitmap.getWidth()) {
resizeBmp = Bitmap.createScaledBitmap(bitmap, 1080, 1440, true);
} else {
resizeBmp = Bitmap.createScaledBitmap(bitmap, 1440, 1080, true);
}
return resizeBmp;
}
压缩图片质量:
public static File compress(Context context, Bitmap bmp2) {
Bitmap bmp = bmp2;
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "pic";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
//图片随机命名(时间戳+随机数)
String fileName = System.currentTimeMillis() +random_23()+ ".jpg";
File file = new File(appDir, fileName);
//addIgnore(图片文件夹地址) 操作:新建文件.nomedia 作用:该文件所在的文件夹里的图片不在系统相册里显示
addIgnore(storePath);
try {
FileOutputStream fos = new FileOutputStream(file);
//通过io流的方式来压缩保存图片
ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 92, baos);
byte[] bytes = baos.toByteArray();
fos.write(bytes);
fos.flush();
fos.close();
//把文件插入到系统图库
//MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
//保存图片后发送广播通知更新数据库
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
return file;
} else {
return file;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private static void addIgnore(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
File ignoreFile = new File(filePath + "/.nomedia");
if (ignoreFile.exists() && ignoreFile.isFile()) {
return;
}
try {
ignoreFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//随机数
public static String random_23() {
String ran="";
Random r = new Random();
for (int i = 0; i < 22; i++)
{
int ran1 = r.nextInt(9);
ran=ran+ran1;
}
return ran;
}
注意bitmap的回收