Android 保存图片到相册 更新图库

一 添加权限

    private void checkNeedPermissions(){
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
         {
          //6.0以上需要动态申请权限
            if ( ContextCompat.checkSelfPermission(this,             
                 Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                 ) {
                //权限申请
                ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                }, 1);
             }
        }
    }
 
    /**
     * 用户权限 申请 的回调方法
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    //如果没有获取权限,那么可以提示用户去设置界面--->应用权限开启权限
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    // 以前是!b
                    if (b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else{
                        //
                        Toast.makeText(MainActivity.this,"您禁止了访问媒体资料库,如果需要使用此功能,请在设置中打开",Toast.LENGTH_SHORT).show();
                        //finish();
                    }
                } else {
                    //获取权限成功提示
                    Toast toast = Toast.makeText(this, "获取权限成功", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
            }
        }
    }
    /**
     * 提示用户去应用设置界面手动开启权限
     */
    private void showDialogTipUserGoToAppSettting() {
 
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("请在-应用设置-权限-中,允许应用使用存储权限来保存用户数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        finish();
                    }
                }).setCancelable(false).show();
    }
 
    /**
     * 跳转到当前应用的设置界面
     */
    private void goToAppSetting() {
        Intent intent = new Intent();
 
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
 
        startActivityForResult(intent, 123);
    }


复制代码

二 本地资源图片、网络资源图片转bety[]

2.1 本地资源图片转bety[]

     * 读取 本地文件,转为字节数组
     * @param url 本地文件路径
     * @return
     * @throws IOException
     */
    private byte[] getImage(String url) throws IOException{
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(url));
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        byte[] temp = new byte[2048];
        int size = 0;
        while ((size = in.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        in.close();
        byte[] content = out.toByteArray();
        return content;
    }


复制代码

2.2 网络资源图片转bety[]

     * 获取 文件 流
     * @param url
     * @return
     * @throws IOException
     */
    private static byte[] getFile(String url) throws IOException{
        URL urlConet = new URL(url);
        HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(4 * 1000);
        InputStream inStream = con .getInputStream();    //通过输入流获取图片数据
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        byte[] data =  outStream.toByteArray();
        return data;
    }


复制代码

三 写入系统图库,更新到相册

    /**
     * 保存图片到指定路径
     * @param context
     * @param *bitmap   要保存的图片
     * @param fileName 自定义图片名称
     */
    public void   saveImageToGallery( Context context, byte[] data, String fileName) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
         fileName = fileName + format.format(new Date())+".JPEG";
        // 保存图片至指定路径
        String storePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()+"LS" ;
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片(80代表压缩20%)
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();
            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //发送广播通知系统图库刷新数据
            System.out.println("发送广播通知系统图库刷新数据");
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
 
            Toast toast=;
 
            if (isSuccess) {
                Toast.makeText(context,"图片已保存至"+file,Toast.LENGTH_SHORT).show()
            } else {
               Toast toast=Toast.makeText(context,"图片保存失败",Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

赞 (0)