NestedScrollView保存成图片截图

/**
 * NestedScrollView保存成图片截图
 */
public class CompressImageActivity extends AppCompatActivity {
    private static final String TAG = "CompressImageActivity";
    private Button btn_ok;
    private NestedScrollView nestedScrollview;
    private ImageView imageView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.compress_image);
        btn_ok = findViewById(R.id.btn_ok);
        nestedScrollview = findViewById(R.id.nestedScrollview);
        imageView = findViewById(R.id.imageView);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = compressImage(getBitmapByView(nestedScrollview));//截取View的屏幕大小并压缩图片
                String savePic = savePic(bitmap);//把获取到的Bitmap对象压缩图片保存到本地中sdcard
                imageView.setImageBitmap(bitmap);//在把获取到的Bitmap对象在imageView中显示出来
                Log.i(TAG, savePic);
            }
        });
    }

    /**
     * 截取scrollview的屏幕
     *
     * @param scrollView
     * @return
     */
    public Bitmap getBitmapByView(NestedScrollView scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        // 获取scrollview实际高度
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();//获取scrollView的屏幕高度
            scrollView.getChildAt(i).setBackgroundColor(
                    Color.parseColor("#ffffff"));
        }
                //如果传的参数不是NestedScrollView,则不需要循环遍历高度
//        h += scrollView.getHeight();//获取scrollView的屏幕高度
//        scrollView.setBackgroundColor(
//                    Color.parseColor("#ffffff"));
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);//把创建的bitmap放到画布中去
        scrollView.draw(canvas);//绘制canvas 画布
        return bitmap;
    }

    /**
     * 压缩图片
     *
     * @param image
     * @return
     */
    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并返回路径地址
     *
     * @param b
     * @return
     */
    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) {
                    Toast.makeText(CompressImageActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    //通知图库更新
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intent.setData(Uri.fromFile(outFile));
                    sendBroadcast(intent);
                } else {
                    Toast.makeText(CompressImageActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                }
                fos.flush();
                fos.close();//最后关闭此文件输出流并释放与此流相关联的任何系统资源。
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fname;
    }
}

注:如果想在手机相册中看到该图片,我们要通知图库更新一下,则要调用一下代码:

//通知图库更新
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intent.setData(Uri.fromFile(outFile));
                    sendBroadcast(intent);

注:参考百度

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值