Android开发中压缩图片的处理
2023-12-15 10:44:13
在我们实际开发中,进行的图片压缩使用的还是挺频繁的,今天我们就具体的了解一下:
public Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
// 循环判断如果压缩后图片是否大于100kb,大于继续压缩
/* while (baos.toByteArray().length / 1024 > 100) {
// 重置baos
baos.reset();
// 这里压缩options%,把压缩后的数据存放到baos中
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
// 每次都减少10
options -= 10;
}*/
// 把压缩后的数据baos存放到ByteArrayInputStream中
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
// 把ByteArrayInputStream数据生成图片
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
将获取到的压缩图片保存到sdcard并返回路径地址:
public String savePic(Bitmap b) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
Locale.US);
File file = Environment.getExternalStorageDirectory();
// 如果文件不存在,则创建一个新文件
if (!file.isDirectory()) {
try {
file.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
String fname = file.getAbsolutePath() + "/Pictures/" + sdf.format(new Date()) + "_order.png";
File outFile = new File(fname);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outFile);//获取FileOutputStream对象
if (fos != null) {
/**
* 压缩图片
* 第一个参数:要压缩成的图片格式
* 第二个参数:压缩率
* 第三个参数:压缩到指定位置
*/
boolean compress = b.compress(Bitmap.CompressFormat.PNG, 90, fos);
if (compress) {
// EasyToast.getDEFAULT().show("保存成功");
//通知图库更新
/* Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(outFile));*/
} else {
}
fos.flush();
fos.close();//最后关闭此文件输出流并释放与此流相关联的任何系统资源。
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fname;
}
以上就是讲解的主要的内容
文章来源:https://blog.csdn.net/qq_36451275/article/details/135010203
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!