安卓下将网络图片保存到相册

这是我所见过的堪称最最最最简单的将图片保存到相册中的方法Plus
废话不多说,直接撸代码

1.对于权限的注册

   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />  
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET"/>

安卓6.0以后一定要加读写权限的判断 否则是保存不了的 这是重点
2.工具类

public class DonwloadSaveImg {
    private static Context context;
    private static String filePath;
    private static Bitmap mBitmap;
    private static String mSaveMessage = "失败";
    private final static String TAG = "PictureActivity";
    private static ProgressDialog mSaveDialog = null;

    public static void donwloadImg(Context contexts, String filePaths) {
        context = contexts;
        filePath = filePaths;
        mSaveDialog = ProgressDialog.show(context, "保存图片", "图片正在保存中,请稍等...", true);
        new Thread(saveFileRunnable).start();
    }

    private static Runnable saveFileRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (!TextUtils.isEmpty(filePath)) { //网络图片
                    // 对资源链接
                    URL url = new URL(filePath);
                    //打开输入流
                    InputStream inputStream = url.openStream();
                    //对网上资源进行下载转换位图图片
                    mBitmap = BitmapFactory.decodeStream(inputStream);
                    inputStream.close();
                }
                saveFile(mBitmap);
                mSaveMessage = "图片保存成功!";
            } catch (IOException e) {
                mSaveMessage = "图片保存失败!";
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }
    };

    private static Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mSaveDialog.dismiss();
            Log.d(TAG, mSaveMessage);
            Toast.makeText(context, mSaveMessage, Toast.LENGTH_SHORT).show();
        }
    };
    /**
     * 保存图片
     * @param bm
     * @throws IOException
     */
    public static void saveFile(Bitmap bm ) throws IOException {
        File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        String fileName = UUID.randomUUID().toString() + ".jpg";
        File myCaptureFile = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        //把图片保存后声明这个广播事件通知系统相册有新图片到来
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(myCaptureFile);
        intent.setData(uri);
        context.sendBroadcast(intent);
    }

3.主活动中权限的判断以及保存图片

public class Main2Activity extends AppCompatActivity {

    private static int REQUEST_PERMISSION_CODE = 1;
    private String path="https://www.baidu.com/img/bd_logo1.png?where=super";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        checkPermission();
    }

    private void checkPermission() {
        //检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //用户已经拒绝过一次,再次弹出权限申请对话框需要给用户一个解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);

        } else {
            Toast.makeText(this, "授权成功!", Toast.LENGTH_SHORT).show();
            Log.e("aaaaa", "checkPermission: 已经授权!");
        }
    }


    public void write(View view) {   //按钮的点击事件
        DonwloadSaveImg.donwloadImg(Main2Activity.this,path);//iPath
    }
}

大功告成!!!!!!希望能够对你有用
反正我是亲测有效

Android平台上,我们可以通过代码来实现将网络图片保存到本地相册的功能。具体实现过程如下: 1. 获取需要下载的图片链接。 2. 创建一个异步任务,利用HTTPURLConnection或者OKHttp框架下载图片。 3. 下载完成后,将图片转换成Bitmap对象。 4. 申请写入文件的权限,并判断SD卡是否可用。 5. 使用File对象创建一个图片文件。 6. 利用FileOutputStream将Bitmap对象写入图片文件中。 7. 刷新相册,确保新添加的图片能够被相册所识别。 至此,保存网络图片相册的功能已经完成。 以下是实现代码: ```java private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... urls) { String url = urls[0]; Bitmap bitmap = null; try { URL imageURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } protected void onPostExecute(Bitmap result) { if (result != null) { // 申请写入文件的权限 if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); return; } // 判断sd卡是否可用 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 创建图片文件 File imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "image_test.jpg"); try { // 将Bitmap对象写入图片文件中 FileOutputStream outputStream = new FileOutputStream(imageFile); result.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // 100表示压缩率,即不压缩 outputStream.flush(); outputStream.close(); // 刷新相册以便查看新添加的图片 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(imageFile); intent.setData(uri); MainActivity.this.sendBroadcast(intent); Toast.makeText(MainActivity.this, "图片保存相册", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } else { Toast.makeText(MainActivity.this, "sd卡不可用", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show(); } } } ``` 在使用时,只需创建一个DownloadImageTask对象,调用execute方法即可: ```java DownloadImageTask downloadImageTask = new DownloadImageTask(); downloadImageTask.execute("http://www.example.com/image.jpg"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安东尼肉店

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值