图片压缩保存 处理三星拍照图片旋转问题的部分方法

来源:互联网 发布:自动签到脚本 python 编辑:程序博客网 时间:2024/04/30 15:10

图片压缩保存


type为了防止本方法被同时调用时命名重复


private void save(String path, int type) {

try {
// 获取bitmap
File img = new File(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.RGB_565;
options.inSampleSize = 2;
FileInputStream fis = new FileInputStream(img);
Bitmap bitmap = BitmapFactory.decodeStream(fis, null, options);
fis.close();
// 根据图片的大小判断quality
int quality = 100;
long length = img.length();
if (length > 1000 * 1024) {
quality = (int) (1000 * 100 * 1024 / length);
if (quality > 100) {
quality = 100;
} else if (quality < 1) {
quality = 1;
}
}
// 存储图片
imageName = TimeUtil.getCurrentDate("yyyyMMddHHmmss") + type + ".jpg";
File file = new File(URLClass.IMAGE_TEMP_PATH + "/" + imageName);
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, quality, fos);
fos.flush();
fos.close();
// System.out.println("sourceLength=" + img.length()
// + "    targetLength=" + file.length() + "   quality="
// + quality);
// 获取drawable 释放bitmap
Drawable drawable = new BitmapDrawable(bitmap);
bitmap = null;
setImageToView(drawable,
URLClass.IMAGE_TEMP_PATH + "/" + imageName, type);
} catch (IOException e) {
e.printStackTrace();
}

}


处理三星拍照图片旋转问题

1产看图片的选择属性看是否选择了

2如果图片旋转了,调用第二个方法

3保存选择后的图片


/**
* 获取图片旋转角度

* @param path
* @return
*/
private int getBitmapDegree(String path) {
int degree = 0;
try {
// 从指定路径下读取图片,并获取其EXIF信息
ExifInterface exifInterface = new ExifInterface(path);
// 获取图片的旋转信息
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}


/**
* 将图片按照某个角度进行旋转

* @param bm
*            需要旋转的图片
* @param degree
*            旋转角度
* @return 旋转后的图片
*/
public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
Bitmap returnBm = null;
// 根据旋转角度,生成旋转矩阵
Matrix matrix = new Matrix();
matrix.postRotate(degree);
try {
// 将原始图片按照旋转矩阵进行旋转,并得到新的图片
returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), matrix, true);
} catch (OutOfMemoryError e) {
}
if (returnBm == null) {
returnBm = bm;
}
if (bm != returnBm) {
bm.recycle();
}
return returnBm;
}

0 0