std::unique_ptr strm(CreateJavaOutputStreamAdaptor(env, jstream, jstorage));
if (!strm.get()) {
return JNI_FALSE;
}
std::unique_ptr encoder(SkImageEncoder::Create(fm));
if (encoder.get()) {
SkBitmap skbitmap;
bitmap->getSkBitmap(&skbitmap);
success = encoder->encodeStream(strm.get(), skbitmap, quality);
}
return success ? JNI_TRUE : JNI_FALSE;
}
可以看到最后调用了函数 encoder->encodeStream(…) 编码保存本地。该函数是调用 skia 引擎来对图片进行编码压缩,对 skia 的介绍将在后文展开。
一段完整的示例代码如下:
// R.drawable.thumb 为 png 图片
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.thumb);
try {
//保存压缩图片到本地
File file = new File(Environment.getExternalStorageDirectory(), “aaa.jpg”);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fs = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fs);
Log.i(TAG, "onCreate: file.length " + file.length());
fs.flush();
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//查看压缩之后的 Bitmap 大小
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
byte[] bytes = outputStream.toByteArray();
Bitmap compress = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Log.i(TAG, "onCreate: bitmap.size = " + bitmap.getByteCount() + " compress.size = " + compress.getByteCount());
首先,我们来看看 quality 参数被设置为 50,质量压缩前后的图片对比,可以看到其尺寸大小并没有变化,但是视觉感受也可以明显地看到图片变的模糊了一些。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GbdESP19-1638156594684)(https://user-gold-cdn.xitu.io/2017/11/13/15fb4a4