想要把页面中的某一部分布局转成图片,这里使用了一种比较简单的做法,那就是View组件显示的内容可以通过cache机制保存为bitmap,我们要获取它的cache先要通过setDrawingCacheEnable方法把cache开启,然后再调用getDrawingCache方法就可 以获得view的cache图片了。
buildDrawingCache方法可以不用调用,因为调用getDrawingCache方法时,若果 cache没有建立,系统会自动调用buildDrawingCache方法生成cache。若果要更新cache, 必须要调用destoryDrawingCache方法把旧的cache销毁,才能建立新的。
当调用setDrawingCacheEnabled方法设置为false, 系统也会自动把原来的cache销毁。
获取cache通常会占用一定的内存,所以通常不需要的时候有必要对其进行清理,通过destroyDrawingCache或setDrawingCacheEnabled(false)实现。
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
代码中的view就是要转换成图片的布局,可以是LinearLayout、RelativeLayout等布局。得到的bitmap可以直接显示在ImageView上,,如果要上传到服务端,可以将得到的bitmap图片转换成Base64字符串String上传。
// 把Bitmap图片转换成Base64字符串String
public static String bitmapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 1.5M的压缩后在100Kb以内,测试得值,压缩后的大小=94486字节,压缩后的大小=74473字节
// 这里的JPEG 如果换成PNG,那么压缩的就有600kB这样.
// 实际项目中,可以根据需要考虑图片压缩以及压缩的质量。
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
byte[] b = baos.toByteArray();
// 在这里获取到图片转换后的字符串,然后就可以将这个字符串当做普通的String字符串参数传给后台
// 如果有很多张图片要上传,那么可以考虑将转换后的Base64字符串添加到一个List里面,一并传给后台。
return android.util.Base64.encodeToString(b, android.util.Base64.DEFAULT);
}
// 根据路径获得图片并压缩,返回bitmap用于显示
public static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, 480, 800);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
//计算图片的缩放质量
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
也可以将bitmap图片保存到本地
public String sdCardDir = Environment.getExternalStorageDirectory() + "/myImage/";
private void saveBitmap(Bitmap bitmap) {
try {
File dirFile = new File(sdCardDir);
if (!dirFile.exists()) { //如果不存在,则新建这个文件夹
dirFile.mkdirs();
}
File file = new File(sdCardDir, imageName + ".jpg");
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(this.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 通知图库更新
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://" + "/sdcard/namecard/")));
}