Android:点击按钮,保存图片到本地相册

Posted Z|Star

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android:点击按钮,保存图片到本地相册相关的知识,希望对你有一定的参考价值。

效果:点击按钮,将ImageView的图片保存到相册中。

activity_main:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent" >
    <Button
        android:layout_width="wrap_content"
        android:id="@+id/tvSave"
        android:layout_marginTop="15dp"
        android:text="保存"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="wrap_content"
        android:id="@+id/tvpath"
        android:layout_marginTop="15dp"
        android:text="保存"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="wrap_content"
        android:id="@+id/tvpath2"
        android:layout_marginTop="15dp"
        android:text="保存"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/imgPingjia2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="15dp"

        android:layout_gravity="center_horizontal"
        android:layout_marginTop="15dp"
        android:src="@mipmap/img_default_bg" />

</LinearLayout>

MainActivity.java

package com.netease.nim.imagesave;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    Button tvSave;
    ImageView imageShowPic;
    TextView tvpath;
    TextView tvpath2;

    private String savedPath = Environment.getExternalStorageDirectory().getAbsolutePath() +
            File.separator  + String.valueOf(System.currentTimeMillis()) + ".png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvpath = findViewById(R.id.tvpath);
        tvpath2 = findViewById(R.id.tvpath2);
        imageShowPic = findViewById(R.id.imgPingjia2);



        imageShowPic.setImageResource( R.mipmap.demo_tribe_header );
        tvSave = findViewById(R.id.tvSave);
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                tvSave.setClickable(false);

//相关权限的申请 存储权限

                try {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED
                            || ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
// 申请一个(或多个)权限,并提供用于回调返回的获取码(用户定义)
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                    } else {
//                        mLDialog.setDialogText("正在保存图片...");
//                        mLDialog.show();
                        saveMyBitmap("AuthCode", createViewBitmap(imageShowPic));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //权限申请的回调
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
// If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    mLDialog.setDialogText("正在保存图片...");
//                    mLDialog.show();
                    try {
                        saveMyBitmap("AuthCode", createViewBitmap(imageShowPic));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    tvSave.setClickable(true);
                    Toast.makeText(MainActivity.this, "请先开启读写权限", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    //使用IO流将bitmap对象存到本地指定文件夹
    public void saveMyBitmap(final String bitName, final Bitmap bitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String filePath = Environment.getExternalStorageDirectory().getPath();
                File file = new File(savedPath);
                try {
                    file.createNewFile();


                    FileOutputStream fOut = null;
                    fOut = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);


                    Message msg = Message.obtain();
                    msg.obj = file.getPath();
                    handler.sendMessage(msg);
//Toast.makeText(PayCodeActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                    fOut.flush();
                    fOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String picFile = (String) msg.obj;
            String[] split = picFile.split("/");
            String fileName = split[split.length - 1];
            try {
                MediaStore.Images.Media.insertImage(getApplicationContext()
                        .getContentResolver(), picFile, fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
// 最后通知图库更新
            sendBroadcast(new Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"
                    + picFile)));
            Toast.makeText(MainActivity.this, "图片保存图库成功", Toast.LENGTH_LONG).show();
//            if (mLDialog != null && mLDialog.isShowing()) {
//                mLDialog.dismiss();
//            }
            tvSave.setClickable(true);
        }
    };
    //将要存为图片的view传进来 生成bitmap对象

    public Bitmap createViewBitmap(View v) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }
}

参考资源:
https://download.csdn.net/download/wangqing830414/11197239

以上是关于Android:点击按钮,保存图片到本地相册的主要内容,如果未能解决你的问题,请参考以下文章

微信简历小程序保存图片

js保存图片到手机

我下载图片,保存到了本地,但相册里没有,图片能在哪?

即拿即用-选择头像,可以选择相册,拍照,查看大图,保存到本地

Android 使用系统相机拍摄照片保存到本地并在系统相册中显示

android将应用中图片保存到系统相册并显示