精华内容
下载资源
问答
  • Android保存图片到本地

    2017-08-21 10:54:20
    Android保存图片到本地 需求 一个很常见的需求,查看大图的同时,点击可以将图片保存到本地 我的步骤使用Gilde获取图片的Drawable Drawable转成Bitmap bigtmap压缩并通过流写入 通知系统图库更新 代码块 - 保存图片,...

    Android保存图片到本地

    需求

    一个很常见的需求,查看大图的同时,点击可以将图片保存到本地

    我的步骤

    1. 使用Gilde获取图片的Drawable
    2. Drawable转成Bitmap
    3. bigtmap压缩并通过流写入
    4. 通知系统图库更新

    代码块

    - 保存图片,流写入,压缩

        public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "nongfaziran");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(file.getPath()))));
        ToastUtil.showShort("保存到" + file.getPath());
    }`
    

    通过glide回调,获取图片Drawable

          mTvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadding();
                GlideUtils.loadImage(Utils.getContext(), urls.get(mViewPager.getCurrentItem()), mIvImg,new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                    @Override
                    public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {
                        hideLoadding();
                        FileUtils.saveImageToGallery(Utils.getContext(), BitmapUtils.drawableToBitmap(resource));
                        showState("保存成功",1);
                    }
    
                    @Override
                    public void onLoadingError(String source, Exception e) {
                        hideLoadding();
                        showState("保存失败",0);
                        ToastUtil.showShort("请检查SD卡并检查网络");
                    }
                });
            }
        });
    

    分享一个Glide封装

    /**
    * Glide封装类
     * Created by fengan on 2017/5/6.
    * Last Update on 2017.6.22 。 添加注解提醒、返回类型、优化代码
    */
    public abstract class GlideUtils {
    
    
    /**
     * 简单图片加载回调
     *
     * @param <T> 图片url 或资源id 或 文件
     * @param <K> 返回的资源,GlideDrawable或者Bitmap或者GifDrawable,ImageView.setImageRecourse设置
     */
    public interface ImageLoadListener<T, K> {
    
        /**
         * 图片加载成功回调
         *
         * @param uri      图片url 或资源id 或 文件
         * @param view     目标载体,不传则为空
         * @param resource 返回的资源,GlideDrawable或者Bitmap或者GifDrawable,ImageView.setImageRecourse设置
         */
        void onLoadingComplete(T uri, ImageView view, K resource);
    
        /**
         * 图片加载异常返回
         *
         * @param source 图片地址、File、资源id
         * @param e      异常信息
         */
        void onLoadingError(T source, Exception e);
    
    }
    
    
    /**
     * 详细加载图片加载回调
     *
     * @param <T> 图片url 或资源id 或 文件
     * @param <K> 返回的资源
     */
    public interface ImageLoadDetailListener<T, K> {
    
        /**
         * 图片加载成功回调
         *
         * @param uri      图片url 或资源id 或 文件
         * @param view     目标载体,不传则为空
         * @param resource 返回的资源,GlideDrawable或者Bitmap或者GifDrawable,ImageView.setImageRecourse设置
         */
        void onLoadingComplete(T uri, ImageView view, K resource);
    
        /**
         * 图片加载异常返回
         *
         * @param source        图片地址、File、资源id
         * @param errorDrawable 加载错误占位图
         * @param e             异常信息
         */
        void onLoadingError(T source, Drawable errorDrawable, Exception e);
    
        /**
         * 加载开始
         *
         * @param source      图片来源
         * @param placeHolder 开始加载占位图
         */
        void onLoadingStart(T source, Drawable placeHolder);
    
    }
    
    
    /**
     * 根据上下文和 url获取 Glide的DrawableTypeRequest
     *
     * @param context 上下文
     * @param url     图片连接
     * @param <T>     Context类型
     * @param <K>     url类型
     * @return 返回DrawableTypeRequst<K> 类型
     */
    private static <T, K> DrawableTypeRequest<K> getDrawableTypeRequest(T context, K url) {
        DrawableTypeRequest<K> type = null;
        try {
            if (context instanceof android.support.v4.app.Fragment) {
                type = Glide.with((android.support.v4.app.Fragment) context).load(url);
            } else if (context instanceof android.app.Fragment) {
                type = Glide.with((android.app.Fragment) context).load(url);
            } else if (context instanceof Activity) {    //包括FragmentActivity
                type = Glide.with((Activity) context).load(url);
            } else if (context instanceof Context) {
                type = Glide.with((Context) context).load(url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return type;
    }
    
    
    /**
     * 图片加载监听类
     *
     * @param <T> 图片链接 的类型
     * @param <K> 图片资源返回类型
     * @param <Z> 返回的图片url
     */
    private static class GlideListener<T, K, Z> implements RequestListener<T, K> {
    
        ImageLoadListener<Z, K> imageLoadListener = null;
        Z url;
        ImageView imageView = null;
    
        GlideListener(ImageLoadListener<Z, K> imageLoadListener, Z url, ImageView view) {
            this.imageLoadListener = imageLoadListener;
            this.url = url;
            this.imageView = view;
        }
    
        GlideListener(ImageLoadListener<Z, K> imageLoadListener, Z url) {
            this.imageLoadListener = imageLoadListener;
            this.url = url;
        }
    
        GlideListener(Z url) {
            this.url = url;
        }
    
        @Override
        public boolean onResourceReady(K resource, T model, Target<K> target, boolean isFromMemoryCache, boolean isFirstResource) {
            if (null != imageLoadListener) {
                if (imageView != null) {
                    imageLoadListener.onLoadingComplete(url, imageView, resource);
                } else {
                    imageLoadListener.onLoadingComplete(url, null, resource);
                }
            }
    
            return false;
        }
    
        @Override
        public boolean onException(Exception e, T model, Target<K> target, boolean isFirstResource) {
    
            //LogUtil.e("Glide图片加载失败:"+e + " 地址为:"+url);
    
            if (imageLoadListener != null) {
                imageLoadListener.onLoadingError(url, e);
            }
            return false;
        }
    }
    
    
    /**
     * 获取存储器上的图片,回调返回GlideDrawable
     *
     * @param context           上下文年
     * @param file              文件File
     * @param imageLoadListener 回调监听器
     */
    public static <T> DrawableRequestBuilder<File> loadImage(T context, @NonNull File file, @NonNull ImageLoadListener<File, GlideDrawable> imageLoadListener) {
        DrawableTypeRequest<File> type = getDrawableTypeRequest(context, file);
        if (type != null) {
            return type.listener(new GlideListener<File, GlideDrawable, File>(imageLoadListener, file));
        } else {
            return null;
        }
    }
    
    /**
     * 获取资源中的图片,回调返回GlideDrawable
     *
     * @param context           上下文
     * @param resourceId        资源id
     * @param imageLoadListener 回调监听器
     */
    public static <T> DrawableRequestBuilder<Integer> loadImage(T context, @DrawableRes int resourceId, @NonNull ImageLoadListener<Integer, GlideDrawable> imageLoadListener) {
        DrawableTypeRequest<Integer> type = getDrawableTypeRequest(context, resourceId);
        if (type != null) {
            return type.listener(new GlideListener<Integer, GlideDrawable, Integer>(imageLoadListener, resourceId));
        } else {
            return null;
        }
    
    }
    
    /**
     * 获取网络图片,回调返回 GlideDrawable
     *
     * @param context           上下文
     * @param url               图片url
     * @param imageLoadListener 回调监听器
     */
    public static <T> DrawableRequestBuilder<String> loadImage(T context, @NonNull final String url, @NonNull ImageLoadListener<String, GlideDrawable> imageLoadListener) {
        DrawableTypeRequest<String> type = getDrawableTypeRequest(context, url);
        if (type != null) {
            return type.listener(new GlideListener<String, GlideDrawable, String>(imageLoadListener, url));
        } else {
            return null;
        }
    
    }
    
    /**
     * 加载存储器上的图片到目标载体
     *
     * @param file      文件File
     * @param imageView 要显示到的图片ImageView
     */
    public static Target<GlideDrawable> loadImage(@NonNull final File file, @NonNull ImageView imageView, ImageLoadListener<File, GlideDrawable> imageLoadListener) {
        return getDrawableTypeRequest(imageView.getContext(), file)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                .skipMemoryCache(true)//跳过内存缓存
                .dontAnimate()
                .listener(new GlideListener<File, GlideDrawable, File>(imageLoadListener, file, imageView))
                .into(imageView);
    }
    
    /**
     * 加载资源中的图片到目标载体
     *
     * @param resourceId 资源id
     * @param imageView  图片View
     */
    public static Target<GlideDrawable> loadImage(@DrawableRes int resourceId, @NonNull ImageView imageView, ImageLoadListener<Integer, GlideDrawable> imageLoadListener) {
        return getDrawableTypeRequest(imageView.getContext(), resourceId)
                .listener(new GlideListener<Integer, GlideDrawable, Integer>(imageLoadListener, resourceId, imageView))
                .into(imageView);
    }
    
    
    /**
     * 加载成圆形头像到普通ImageView,有动画效果
     *
     * @param url               图片url
     * @param imageView         要显示到的ImageView
     * @param imageLoadListener 加载回调监听器
     * @param parms             设置占位符和加载失败图片(可变参数默认两张,第一张为占位符,第二张是默认图片)
     * @return 返回Target<GlideDrawable>
     */
    public static Target<GlideDrawable> loadCircleImage(@NonNull String url, @NonNull ImageView imageView, ImageLoadListener<String, GlideDrawable> imageLoadListener, int... parms) {
        DrawableTypeRequest<String> type = getDrawableTypeRequest(imageView.getContext(), url);
        if (parms != null && parms.length > 0) {
            type.placeholder(parms[0]);   //占位符
            if (parms.length > 1) {
                type.error(parms[1]);    //图片加载失败显示图片
            }
        }
        type.transform(new CircleTransform(imageView.getContext()));
        return type.listener(new GlideListener<String, GlideDrawable, String>(imageLoadListener, url, imageView))
                .into(imageView);
    
    }
    
    
    /**
     * 加载网络图片到指定Imageview,支持CircleImageView
     *
     * @param url               图片url
     * @param imageView         要显示的Imageview
     * @param imageLoadListener 图片加载回调
     * @param parms             第一个是error的图片
     */
    public static <T> Target<GlideDrawable> loadImage(T context, @NonNull String url, @NonNull ImageView imageView, ImageLoadListener<String, GlideDrawable> imageLoadListener, int... parms) {
        DrawableTypeRequest<String> type = getDrawableTypeRequest(context, url);
        if (type != null) {
            type.asBitmap();
            if (parms != null && parms.length > 0) {
                type.placeholder(parms[0]);   //占位符
                if (parms.length > 1) {
                    type.error(parms[1]);    //图片加载失败显示图片
                }
            }
    
            //单张CircleImageView不允许动画,不然会不显示,
            if (imageView instanceof nfzr.zr.nf.nfzr.com.nongfaziran.nfzr.view.CircleImageView) {
                type.dontAnimate();
            }
            return type
                    .listener(new GlideListener<String, GlideDrawable, String>(imageLoadListener, url, imageView))
                    .into(imageView);
        } else {
            return null;
        }
    
    }
    
    /**
     * 加载一帧视频,添加圆角
     *
     * @param url       图片地址
     * @param imageView 要加载到的ImageView
     */
    public static Target<GlideDrawable> loadImageFormVideo(@NonNull String url, @NonNull ImageView imageView) {
        return getDrawableTypeRequest(imageView.getContext(), url)
                .override(SizeUtil.dp2px(150), SizeUtil.dp2px(150))
                //.placeholder(android.R.drawable.picture_frame)   //占位图
                .dontAnimate()
                .into(imageView);
    }
    
    
    public static <T> Target<GlideDrawable> loadImageDetail(final T context, @NonNull final String url, @NonNull final ImageView imageView, final Drawable drawable, final ImageLoadDetailListener<String, GlideDrawable> imageLoadListener) {
        DrawableTypeRequest<String> type = getDrawableTypeRequest(context, url);
        if (type != null) {
            return type.into(new SimpleTarget<GlideDrawable>() {
                @Override
                public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                    if (imageView != null && resource != null) {
                        imageView.setImageDrawable(resource);
                    }
                    if (imageLoadListener != null) {
                        imageLoadListener.onLoadingComplete(url, imageView, resource);
                    }
    
                }
    
                @Override
                public void onStart() {
                    super.onStart();
                    if (drawable != null && imageView != null) {
                        imageView.setImageDrawable(drawable);
                    }
    
                }
    
                @Override
                public void onLoadStarted(Drawable placeholder) {
                    super.onLoadStarted(placeholder);
                    if (imageLoadListener != null) {
                        imageLoadListener.onLoadingStart(url, placeholder);
                    }
    
                }
    
                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                    super.onLoadFailed(e, errorDrawable);
                    if (imageLoadListener != null) {
                        imageLoadListener.onLoadingError(url, errorDrawable, e);
                    }
                }
            });
        } else {
            return null;
        }
    
    }
    
    
    /**
     * 加载bitmap,回调返回 Bitmap
     *
     * @param context           上下文
     * @param url               图片url
     * @param imageLoadListener 图片加载监听器
     * @param <T>               上下文类型
     */
    public static <T> BitmapRequestBuilder<String, Bitmap> loadImageBitmap(T context, @NonNull String url,@NonNull ImageLoadListener<String, Bitmap> imageLoadListener) {
        DrawableTypeRequest<String> type = getDrawableTypeRequest(context, url);
        if (type != null) {
            return type.asBitmap()
                    .listener(new GlideListener<String, Bitmap, String>(imageLoadListener, url));
        }else{
            return null;
        }
    }
    
    
    /**
     * 加载GifDrawable,回调返回 GifDrawable
     *
     * @param context           上下文
     * @param url               图片url
     * @param imageLoadListener 图片加载监听器
     */
    public static <T> GifRequestBuilder<String> loadImageGif(T context, @NonNull String url,@NonNull ImageLoadListener<String, GifDrawable> imageLoadListener) {
        DrawableTypeRequest<String> type = getDrawableTypeRequest(context, url);
        if (type != null) {
            return type.asGif()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .listener(new GlideListener<String, GifDrawable, String>(imageLoadListener, url));
    
        }else{
            return null;
        }
    }
    
    
    /**
     * 加载Gif的一张图片到ImageView
     *
     * @param url               图片url
     * @param imageLoadListener 图片加载监听器
     *                          @param imageView 
     *                          @param drawable 缩略图,可以为空
     */
    public static Target<Bitmap> loadImageGifSingle(@NonNull String url, @NonNull ImageView imageView, ImageLoadListener<String, Bitmap> imageLoadListener, Drawable drawable) {
    
        DrawableTypeRequest<String> type = getDrawableTypeRequest(imageView.getContext(),url);
        return type.asBitmap()
                .placeholder(drawable)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .listener(new GlideListener<String, Bitmap, String>(imageLoadListener, url))
                .into(imageView);
    }
    
    
    /**
     * 加载gif图片到指定ImageView
     *
     * @param url               图片Url
     * @param imageView         图片View
     * @param imageLoadListener 图片加载监听器
     */
    public static Target<GifDrawable> loadImageGif(@NonNull String url, @NonNull ImageView imageView, ImageLoadListener<String, GifDrawable> imageLoadListener) {
        DrawableTypeRequest<String> type = getDrawableTypeRequest(imageView.getContext(),url);
        return type.asGif()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .listener(new GlideListener<String, GifDrawable, String>(imageLoadListener, url, imageView))
                .into(imageView);
    }
    
    
    /**
     * 释放内存
     *
     * @param context 上下文
     */
    public static void clearMemory(Context context) {
        Glide.get(context).clearMemory();
    }
    
    
    /**
     * 取消所有正在下载或等待下载的任务。
     *
     * @param context 上下文
     */
    public static void cancelAllTasks(Context context) {
        Glide.with(context).pauseRequests();
    }
    
    /**
     * 恢复所有任务
     */
    public static void resumeAllTasks(Context context) {
        Glide.with(context).resumeRequests();
    }
    
    /**
     * 清除磁盘缓存
     *
     * @param context 上下文
     */
    public static void clearDiskCache(final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(context).clearDiskCache();
            }
        }).start();
    }
    
    
    /**
     * 清除所有缓存
     *
     * @param context 上下文
     */
    public static void cleanAll(Context context) {
        clearDiskCache(context);
        clearMemory(context);
    }
    

    }
    `


    /**
    * Created by fengan on 2017/5/25.
    */
    public class CircleTransform extends BitmapTransformation {
    public CircleTransform(Context context) {
        super(context);
    }
    
    @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return circleCrop(pool, toTransform);
    }
    
    private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;
    
        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;
    
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
    
        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }
    
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return result;
    }
    
    @Override public String getId() {
        return getClass().getName();
    }
    }
    

    Drawable转bigmap

    public class BitmapUtils {
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }
    }
    
    border="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=423849475&auto=1&height=66">
    展开全文
  • Android 保存图片到本地

    千次阅读 2017-10-27 20:33:56
    Android下载图片到本地

    现在项目中基本都有这样的需求,把图片保存到本地相册

    这是一个工具类代码如下:

    public class ImgUtils {
        /**
         * 保存文件到指定路径
         */
        public static boolean saveImageToGallery(Context context, Bitmap bmp){
            // 首先保存图片
            String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
            File appDir = new File(storePath);
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            String fileName = System.currentTimeMillis() + ".jpg";
            File file = new File(appDir, fileName);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                //通过io流的方式来压缩保存图片
                boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
                fos.flush();
                fos.close();
    
                //把文件插入到系统图库
                //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
    
                //保存图片后发送广播通知更新数据库
                Uri uri = Uri.fromFile(file);
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                if (isSuccess) {
                    return true;
                } else {
                    return false;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    }
    

    Android 6.0的手机需要先申请权限,拿到权限后再保存,否则会失败
    添加依赖

    compile ‘pub.devrel:easypermissions:0.3.0’

    实现EasyPermissions.PermissionCallbacks,重写获取权限的方法

        @OnClick(R.id.save)
        public void save() {
            requestPermission();
        }
    
        /**
         * 请求读取sd卡的权限
         */
        private void requestPermission() {
            if (Build.VERSION.SDK_INT >= 23) {
                //读取sd卡的权限
                String[] mPermissionList = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                if (EasyPermissions.hasPermissions(getApplicationContext(), mPermissionList)) {
                    //已经同意过
                    saveImage();
                } else {
                    //未同意过,或者说是拒绝了,再次申请权限
                    EasyPermissions.requestPermissions(
                            this,  //上下文
                            "保存图片需要读取sd卡的权限", //提示文言
                            REQUEST_CODE_SAVE_IMG, //请求码
                            mPermissionList //权限列表
                    );
                }
            } else {
                saveImage();
            }
        }
    
    
        /**
         * 保存图片
         */
        private void saveImage() {
            System.out.println(" 6666 ");
            System.out.println(current + " current ");
            final String urls = imagesUrl.get(current);
            System.out.println(urls + " url ");
            System.out.println(" 8888 ");
    
    //        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.fj);
    
            new Thread(new Runnable() {
                Bitmap bitmap = null;
                @Override
                public void run() {
                    URL url = null;
                    try {
                        url = new URL("http://test.zuihou99.com" + urls);
                        InputStream is = null;
                        BufferedInputStream bis = null;
                        try {
                            is = url.openConnection().getInputStream();
                            bis = new BufferedInputStream(is);
                            bitmap = BitmapFactory.decodeStream(bis);
    
                            boolean isSaveSuccess = ImgUtils.saveImageToGallery(getApplicationContext(), bitmap);
                            if (isSaveSuccess) {
                                Looper.prepare();
                                Toast.makeText(getApplicationContext(), "保存图片成功", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            } else {
                                Looper.prepare();
                                Toast.makeText(getApplicationContext(), "保存图片失败,请稍后重试", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
    
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    
    
        /**
         * 根据图片的url路径获得Bitmap对象
         *
         * @param url
         * @return
         */
        private Bitmap decodeUriAsBitmapFromNet(String url) {
            URL fileUrl = null;
            Bitmap bitmap = null;
    
            try {
                fileUrl = new URL(url);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
    
            try {
                HttpURLConnection conn = (HttpURLConnection) fileUrl
                        .openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }
    
    
        //授权结果,分发下去
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            // Forward results to EasyPermissions
            //跳转到onPermissionsGranted或者onPermissionsDenied去回调授权结果
            EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        }
    
    
        //同意授权
        @Override
        public void onPermissionsGranted(int requestCode, List<String> list) {
            saveImage();
        }
    
        //拒绝授权
        @Override
        public void onPermissionsDenied(int requestCode, List<String> perms) {
            if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                //打开系统设置,手动授权
                new AppSettingsDialog.Builder(this).build().show();
            }
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
                //拒绝授权后,从系统设置了授权后,返回APP进行相应的操作
                saveImage();
            }
        }
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // TODO: add setContentView(...) invocation
            ButterKnife.bind(this);
        }

    这样就可以了,有不对的欢迎指出

    这里附上源码http://download.csdn.net/download/qq_23668969/10042303

    展开全文
  • android保存图片到本地

    千次阅读 2015-12-22 11:18:24
    我将其写到了一个异步线程中: class SaveImage extends AsyncTask{ @Override protected Void doInBackground...//保存到本地 FileOutputStream fos = null; BufferedOutputStream bos = null; ByteArray

    我将其写到了一个异步线程中:

    class SaveImage extends AsyncTask<Void,Void,Void>{


    @Override
    protected Void doInBackground(Void... params) {

    //保存到本地
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    ByteArrayOutputStream baos = null;
    isUploading = true;
    try{
    baos = new ByteArrayOutputStream();
    cutBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] byteArray = baos.toByteArray();
    // 将字节数组写入到刚创建的图片文件中
    imgFile = new File(FileManager.getSaveFilesPath(),UUID.randomUUID().toString()+".png");
    fos = new FileOutputStream(imgFile);
    bos = new BufferedOutputStream(fos);
    bos.write(byteArray);

    }catch(Exception e){
    showShortToast("图片上传失败");
    }finally{

    if(ValidateUtils.isNotNullObj(baos)) {
    try {
    baos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    if(ValidateUtils.isNotNullObj(bos)) {
    try {
    bos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    if(ValidateUtils.isNotNullObj(fos)) {
    try {
    fos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    return null;
    }

    @Override
    protected void onPostExecute(Void result) {

    tvProgress.setVisibility(View.VISIBLE);
    uploadingProgressView.setVisibility(View.VISIBLE);

    }

    }


    展开全文
  • Android 保存图片到本地(兼容Android 10+) 图片保存在 DCIM 公开目录 大于 28 需使用 MediaStore 小于 29 直接 new FIle public class ImageSaveUtil { /** * 29 以下,需要提前申请文件读写权限 * 29及29以上的...

    Android 保存图片到本地(兼容Android 10+)
    图片保存在 DCIM 公开目录
    大于 28 需使用 MediaStore
    小于 29 直接 new FIle

    public class ImageSaveUtil {
    
        /**
         * 保存图片到公共目录
         * 29 以下,需要提前申请文件读写权限
         * 29及29以上的,不需要权限
         * 保存的文件在 DCIM 目录下
         *
         * @param context 上下文
         * @param bitmap  需要保存的bitmap
         * @param format  图片格式
         * @param quality 压缩的图片质量
         * @param recycle 完成以后,是否回收Bitmap,建议为true
         * @return 文件的 uri
         */
        @Nullable
        public static Uri saveAlbum(Context context, Bitmap bitmap, Bitmap.CompressFormat format, int quality, boolean recycle) {
            String suffix;
            if (Bitmap.CompressFormat.JPEG == format)
                suffix = "JPG";
            else
                suffix = format.name();
            String fileName = System.currentTimeMillis() + "_" + quality + "." + suffix;
            if (Build.VERSION.SDK_INT < 29) {
                if (!isGranted(context)) {
                    Log.e("ImageUtils", "save to album need storage permission");
                    return null;
                }
                File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                File destFile = new File(picDir, fileName);
                if (!save(bitmap, destFile, format, quality, recycle))
                    return null;
                Uri uri = null;
                if (destFile.exists()) {
                    uri = Uri.parse("file://" + destFile.getAbsolutePath());
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intent.setData(uri);
                    context.sendBroadcast(intent);
                }
                return uri;
            } else {
                // Android 10 使用
                Uri contentUri;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else
                    contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
                ContentValues contentValues = new ContentValues();
                contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
                contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
                contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/");
                // 告诉系统,文件还未准备好,暂时不对外暴露
                contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
                Uri uri = context.getContentResolver().insert(contentUri, contentValues);
                if (uri == null) return null;
                OutputStream os = null;
                try {
                    os = context.getContentResolver().openOutputStream(uri);
                    bitmap.compress(format, quality, os);
                    // 告诉系统,文件准备好了,可以提供给外部了
                    contentValues.clear();
                    contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
                    context.getContentResolver().update(uri, contentValues, null, null);
                    return uri;
                } catch (Exception e) {
                    e.printStackTrace();
                    // 失败的时候,删除此 uri 记录
                    context.getContentResolver().delete(uri, null, null);
                    return null;
                } finally {
                    try {
                        if (os != null)
                            os.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        }
    
        private static boolean save(Bitmap bitmap, File file, Bitmap.CompressFormat format, int quality, boolean recycle) {
            if (isEmptyBitmap(bitmap)) {
                Log.e("ImageUtils", "bitmap is empty.");
                return false;
            }
            if (bitmap.isRecycled()) {
                Log.e("ImageUtils", "bitmap is recycled.");
                return false;
            }
            if (!createFile(file, true)) {
                Log.e("ImageUtils", "create or delete file <$file> failed.");
                return false;
            }
            OutputStream os = null;
            boolean ret = false;
            try {
                os = new BufferedOutputStream(new FileOutputStream(file));
                ret = bitmap.compress(format, quality, os);
                if (recycle && !bitmap.isRecycled()) bitmap.recycle();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (os != null)
                        os.close();
                } catch (IOException e) {
                    // ignore
                }
            }
            return ret;
        }
    
        private static boolean isEmptyBitmap(Bitmap bitmap) {
            return bitmap == null || bitmap.isRecycled() || bitmap.getWidth() == 0 || bitmap.getHeight() == 0;
        }
    
        private static boolean createFile(File file, boolean isDeleteOldFile) {
            if (file == null) return false;
            if (file.exists()) {
                if (isDeleteOldFile) {
                    if (!file.delete()) return false;
                } else
                    return file.isFile();
            }
            if (!createDir(file.getParentFile())) return false;
            try {
                return file.createNewFile();
            } catch (IOException e) {
                return false;
            }
        }
    
        private static boolean createDir(File file) {
            if (file == null) return false;
            if (file.exists())
                return file.isDirectory();
            else
                return file.mkdirs();
        }
    
        private static boolean isGranted(Context context) {
            return (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE));
        }
    }
    
    展开全文
  • Android保存图片到本地图库 主要通过ContentResolver和Images.Media类相关的功能实现。通过ContentResolver的Insert()方法将图片插入图库和update()方法更新图库。
  • if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//重要的看这里,这是Android 10以上的 values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Camera"); } else { //这是以下的 values.put(MediaStore...
  • Android 图片保存到本地,更新相册,并且打开微信发送图片的时候,可以被识别 测了一下,大部分手机都可以适配,不适配的再找别的吧 public static void saveImageToGallery(Bitmap mBitmap) { if (!Environment....
  • android 保存图片到本地系统相册

    千次阅读 2018-07-03 12:18:36
    工具类:public class ImgUtils { //保存文件指定路径 public static boolean saveImageToGallery(Context context, Bitmap ... // 首先保存图片 dearxy是可以改的 String storePath = Environment.getExterna...
  • 一个保存图片到本地的方法:直接传入bitmap就可以使用:public static void saveToSystemGallery(Context context, Bitmap bmp) { // 首先保存图片 File appDir = new File(Environment....
  • 首先贴一段代码 -- 这个是先生成一个本地的路径,将图片保存到这个文件中,然后扫描下sd卡。让系统相册重新加载下 。缺点就是只能保存到DCIM的文 件夹下边,暂时不知道怎么获取系统相机的路径,网上找了下说了好...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 777
精华内容 310
关键字:

android保存图片到本地