本文主要是android中几个图片处理的工具,包括(拼接图片,截屏,将控件转换成图片,drawable转成图片,保存bitmap到指定路径)
当点击按钮时,将当前手机屏幕中显示的页面以图片的形式保存起来
拼接图片
竖直拼接
private Bitmap add2Bitmap(Bitmap first, Bitmap second) { int width = first.getWidth(); int height = first.getHeight() + second.getHeight(); Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(result); canvas.drawBitmap(first, 0, 0, null); canvas.drawBitmap(second, 0, first.getHeight(), null); return result; }
横向拼接
private Bitmap add2Bitmap(Bitmap first, Bitmap second) { int width = first.getWidth() + second.getWidth(); int height = first.getHeight(); Bitmap result = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(result); canvas.drawBitmap(first, 0, 0, null); canvas.drawBitmap(second, first.getWidth(), 0, null); return result; }
截屏-将当前屏幕图片转成Bitmap
private Bitmap captureScreen(Activity context) { View cv = context.getWindow().getDecorView(); Bitmap bmp = Bitmap.createBitmap(cv.getWidth(), cv.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); cv.draw(canvas); return bmp; }
将当前控件转成Bitmap——WebView
private Bitmap captureWebView(WebView webView) { Picture snapShot = webView.capturePicture(); Bitmap bmp = Bitmap.createBitmap(snapShot.getWidth(), snapShot.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); snapShot.draw(canvas); return bmp; }
将drawable转换成bitmap
private Bitmap draw2Bit(Drawable drawable) { int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;// 取drawable的颜色格式 Bitmap bitmap = Bitmap.createBitmap(width, height, config);// 建立对应bitmap Canvas canvas = new Canvas(bitmap);// 建立对应bitmap的画布 drawable.setBounds(0, 0, width, height); drawable.draw(canvas);// 把drawable内容画到画布中 return bitmap; }
保存bitmap到指定路径
public void saveFile(Bitmap bitmap, String filename) { try { File file = new File(Environment.getExternalStorageDirectory(), filename); FileOutputStream fileOutputStream = new FileOutputStream(file); if (fileOutputStream != null) { bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }