Android保存View转Bitmap并到本地图库实时更新

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33330887/article/details/83652409

参考张大神的http://stormzhang.github.io/android/2014/07/24/android-save-image-to-gallery/

最开始我想的是截屏保存更方便,但很丑,于是查了下资料。不到30分钟就弄出来了,很顺利,还是感谢那些开源分享的大神们

遇到没做过的,先思考,再动手找解决办法。哈哈。下面是我项目中的的代码,可以参考

private void save(final LinearLayout mView){
    // 获取图片某布局
    mView.setDrawingCacheEnabled(true);
    mView.buildDrawingCache();

    mHandler.postDelayed(new Runnable() {

        @Override
        public void run() {
            // 要在运行在子线程中
              bmp = mView.getDrawingCache(); // 获取图片
            savePicture(bmp, "zzp_sale.png");// 保存图片
            mView.destroyDrawingCache(); // 保存过后释放资源
        }
    },100);
}
 public void savePicture(Bitmap bm, String fileName) {
        Log.i("xing", "savePicture: ------------------------");
        if (null == bm) {
            Log.i("xing", "savePicture: ------------------图片为空------");
            return;
        }
        //建立指定文件夹
        File foder = new File(Environment.getExternalStorageDirectory() , "zzp_sale");
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            //压缩保存到本地
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    myCaptureFile.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + myCaptureFile.getPath())));

        Toast.makeText(context, "保存成功!", Toast.LENGTH_SHORT).show();

    }

猜你喜欢

转载自blog.csdn.net/qq_33330887/article/details/83652409