释放双眼,带上耳机,听听看~!
缩放
public static void resize(Bitmap bitmap, File outputFile, int maxWidth, int maxHeight) {
try {
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
// 图片大于最大高宽,按大的值缩放
if (bitmapWidth > maxHeight || bitmapHeight > maxWidth) {
float widthScale = maxWidth * 1.0f / bitmapWidth;
float heightScale = maxHeight * 1.0f / bitmapHeight;
//取小值
float scale = Math.min(widthScale, heightScale);
Matrix matrix = new Matrix();
//图片变换处理 缩放
matrix.postScale(scale, scale);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
}
FileOutputStream out = new FileOutputStream(outputFile);
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
//保存图片
public static void saveBitmap(String outputPath, Bitmap bitmap) {
// save image
FileOutputStream out = null;
try {
out = new FileOutputStream(outputPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//base64转bitmap
public static Bitmap base64tobitmap(String image) {
if (TextUtils.isEmpty(image)) {
return null;
}
byte[] bytes = Base64.decode(image.getBytes(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}
/**
* 加载本地图片
*
* @param url
* @return
*/
public static Bitmap getLoacalBitmap(String url) {
try {
FileInputStream fis = new FileInputStream(url);
return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//旋转拍照生成的图片的方向
public static Bitmap getBitmapByUrl(byte[] data,int fangxiang) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
// 根据拍摄的方向旋转图像(纵向拍摄时要需要将图像选择90度)
Matrix matrix = new Matrix();
matrix.setRotate(fangxiang);
bitmap = FileUtils.comp(Bitmap
.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true));
} catch (Exception e) {
e.printStackTrace();
bitmap.recycle();
bitmap = null;
System.gc();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
fis = null;
}
}
return bitmap;
}
这篇博客介绍了Android中图片处理的一些常见操作,包括如何缩放图片以适应最大尺寸,如何保存Bitmap到指定路径,如何将Base64字符串转换为Bitmap对象,以及如何加载和旋转本地图片。示例代码提供了实用的方法,适用于Android应用开发中的图片处理场景。

1830

被折叠的 条评论
为什么被折叠?



