【GT-安卓应用开发之长按保存图片】

前言:微信预览图片,长按会出现一个弹出框,其中会有一个“保存图片”。今天正好做了一个类似的小功能,特意写了一个小demo来记录一下。

        首先,介绍一下该demo:主界面有一个ImageView显示本人的微信二维码,要实现的功能是长按二维码弹出提示框,告知用户图片保存的路径,点击保存后开始保存图片,保存成功后Toast通知用户。

        界面效果如下:

        

        长按二维码弹出框效果如下:

        

        关键代码:

        1、弹出框

        

private void popSave() {
    View view = View.inflate(this, R.layout.pop_save, null);
    tv = view.findViewById(R.id.tv);
    qd = view.findViewById(R.id.qd);
    qx = view.findViewById(R.id.qx);
    newDialog = new DialogCircle(this, DensityUtil.dip2px(this, width / 4), DensityUtil.dip2px(this, height / 8), view,
            R.style.dialog);
    newDialog.setCancelable(false);
    tv.setText("下载路径:"+path);
    qd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            saveBitmap(save,path);
            newDialog.dismiss();
        }
    });
    newDialog.show();
    qx.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            newDialog.dismiss();
        }
    });
}

        2、保存图片

public void saveBitmap(View view, String filePath) {

    // 创建对应大小的bitmap
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
            Bitmap.Config.RGB_565);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);

    //存储
    FileOutputStream outStream = null;
    File file = new File(filePath);
    if (file.isDirectory()) {//如果是目录不允许保存
        Toast.makeText(MainActivity.this, "该路径为目录路径", Toast.LENGTH_SHORT).show();
        return;
    }
    try {
        outStream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
        outStream.flush();
        Toast.makeText(MainActivity.this, "图片保存成功", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("error", e.getMessage() + "#");
        Toast.makeText(MainActivity.this, "图片保存失败", Toast.LENGTH_SHORT).show();
    } finally {
        try {
            bitmap.recycle();
            if (outStream != null) {
                outStream.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

        3、申请权限

public void requestAllPower() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.INTERNET}, 1);
        }
    }
}

        最后,附上demo地址

猜你喜欢

转载自blog.csdn.net/qq_17433217/article/details/83105106