欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android--解决图片保存到相册显示1970年1月1日 8:00的问题

程序员文章站 2022-06-05 15:56:12
import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics... ......
import android.content.context;
import android.content.intent;
import android.database.cursor;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.graphics.canvas;
import android.graphics.matrix;
import android.graphics.paint;
import android.graphics.rect;
import android.media.mediascannerconnection;
import android.net.uri;
import android.os.environment;
import android.provider.mediastore;
import android.view.view;


public class pictureutils {

    private static string tag = pictureutils.class.getsimplename();

    private static int code_width = 60;
    private static int code_height = 60;

    private pictureutils() {

    }

    /**
     * 保存一张或者多张图片到图库
     */
    public static void saveimagelisttogallery(final baseactivity context,
            final list<string> imglist, final onsaveimgcallback callback) {

        if (context == null) {
            logutils.dtag(tag, "context 不能为null");
            return;
        }

        rxpermissionsutils.getinstance()
                .requestpermission(context, rxpermissionsutils.read_and_write_permission,
                        new rxpermissionsutils.onpermissionrequestcallback() {
                            @override
                            public void onsuccess() {
                                if (imglist == null) {
                                    logutils.dtag(tag, "图片数组为 null");
                                    return;
                                }

                                // 保存图片到图库
                                saveimagelisttogalleryprivate(context, imglist, callback);

                            }

                            @override
                            public void onfail() {
                                toastutils.showshort("请在设置授予应用存储权限^_^");
                                permissionutils.launchappdetailssettings();
                            }
                        });

    }

    /**
     * 保存多张图片
     */
    private static void saveimagelisttogalleryprivate(baseactivity context, list<string> imglist,
            final onsaveimgcallback callback) {

        observable.just(imglist)
                .observeon(schedulers.io())
                .flatmap(new function<list<string>, observablesource<boolean>>() {
                    @override
                    public observablesource<boolean> apply(list<string> strings) throws exception {

                        for (string filepath : strings) {

                            if (filepath.startswith("http://") || filepath.startswith("https://")) {

                                bitmap bmp = glide.with(baseapplication.getinstance())
                                        .asbitmap()
                                        .load(filepath)
                                        .submit()
                                        .get();

                                saveimagetogallery(baseapplication.getinstance(), bmp, filepath);

                            } else {

                                bitmap bmp = bitmapfactory.decodefile(filepath);

                                saveimagetogallery(baseapplication.getinstance(), bmp, filepath);
                            }

                        }

                        return observable.just(true);
                    }
                })
                .observeon(androidschedulers.mainthread())
                .subscribe(new observer<boolean>() {
                    disposable md;

                    @override
                    public void onsubscribe(disposable d) {
                        md = d;
                        if (callback != null) {
                            callback.onsavestart();
                        }
                    }

                    @override
                    public void onnext(boolean aboolean) {
                        toastutils.showshort("图片已成功保存到系统相册^_^");
                        if (callback != null) {
                            callback.onsavesuccess();
                        }
                    }

                    @override
                    public void onerror(throwable e) {
                        if (md != null) {
                            md.dispose();
                        }
                        if (callback != null) {
                            callback.onsavefail();
                        }
                    }

                    @override
                    public void oncomplete() {
                        if (md != null) {
                            md.dispose();
                        }
                    }
                });


    }

    /**
     * 保存 bitmap 到相册 获得路径
     */
    public static string saveimagetogallery(context context, bitmap bmp, string imageurl) {

        if (!sdcardutils.issdcardenablebyenvironment()) {
            logutils.dtag(tag, "内存卡不可用");
            return null;
        }

        // 首先保存图片
        file appdir = new file(environment.getexternalstoragedirectory().getabsolutepath(),
                networkconstants.filekey.commonlib_share_code_dir_name);// 获取文件存储路径

        if (!appdir.exists()) {
            boolean iscreate = appdir.mkdir();
            if (!iscreate) {
                return null;
            }
        }

        // 创建文件 截取,取出名字
        string url_truncated = string.valueof(system.currenttimemillis());
        string filename = "mryt_share_code" + "_" + url_truncated;
        file file = new file(appdir, filename);
        fileutils.deletefile(file);
        if (fileutils.isfileexists(file)) {
            logutils.dtag(tag, file.getabsolutepath());
            return file.getabsolutepath();
        }
        try {
            fileoutputstream fos = new fileoutputstream(file);
            bmp.compress(bitmap.compressformat.jpeg, 100, fos);
            fos.flush();
            fos.close();
            // 插入图库
            /**mediastore.images.media
                    .insertimage(context.getcontentresolver(), file.getabsolutepath(), filename,
                            string.valueof(system.currenttimemillis()));*/
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        } catch (ioexception e) {
            e.printstacktrace();
        }
        // 最后通知图库更新

        /**mediascannerconnection.scanfile(context, new string[]{file.getabsolutepath()}, null,
                new mediascannerconnection.onscancompletedlistener() {
                    @override
                    public void onscancompleted(string path, uri uri) {

                    }
                });*/
        try {
            savephototomedia(context, file, filename);
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        }
        return file.getabsolutepath();
    }

    /**
     * 保存 bitmap 到相册 获得路径 不传递文件名称 用时间后缀
     */
    public static string saveimagetogallery(context context, bitmap bmp) {
        // 首先保存图片
        file appdir = context.getexternalfilesdir(
                networkconstants.filekey.commonlib_share_code_dir_name);// 获取文件存储路径
        if (appdir != null && !appdir.exists()) {
            boolean iscreate = appdir.mkdir();
            if (!iscreate) {
                return null;
            }
        }
        if (!sdcardutils.issdcardenablebyenvironment()) {
            logutils.dtag(tag, "内存卡不可用");
            return null;
        }

        // 创建文件 截取,取出名字
        string url_truncated = string.valueof(system.currenttimemillis());
        string filename = "mryt_share_code" + "_" + url_truncated;
        file file = new file(appdir, filename);
        if (fileutils.isfileexists(file)) {
            logutils.dtag(tag, file.getabsolutepath());
            return file.getabsolutepath();
        }
        try {
            fileoutputstream fos = new fileoutputstream(file);
            bmp.compress(bitmap.compressformat.jpeg, 100, fos);
            fos.flush();
            fos.close();
            // 插入图库
            /**mediastore.images.media
             .insertimage(context.getcontentresolver(), file.getabsolutepath(), filename,
             string.valueof(system.currenttimemillis()));*/
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        } catch (ioexception e) {
            e.printstacktrace();
        }
        // 最后通知图库更新
//        context.sendbroadcast(new intent(intent.action_media_scanner_scan_file, uri.fromfile(file)));
        /**mediascannerconnection.scanfile(context, new string[]{file.getabsolutepath()}, null,
         new mediascannerconnection.onscancompletedlistener() {
        @override public void onscancompleted(string path, uri uri) {
        }
        });*/

        try {
            savephototomedia(context, file, filename);
            toastutils.showshort("图片已成功保存到相册");
        } catch (filenotfoundexception e) {
            e.printstacktrace();
            toastutils.showshort("图片保存失败");
        }
        return file.getabsolutepath();
    }

    public static bitmap getbitmapfromview(context context, view view) {
        view.setdrawingcacheenabled(true);
        //启用drawingcache并创建位图
        view.builddrawingcache();
        //创建一个drawingcache的拷贝,因为drawingcache得到的位图在禁用后会被回收
        bitmap bitmap = bitmap.createbitmap(view.getdrawingcache());
        //禁用drawingcahce否则会影响性能
        view.setdrawingcacheenabled(false);
        return bitmap;
    }

    //图片上绘制文字
    public static bitmap drawtexttobitmap(bitmap bitmap, string text,
            paint paint, rect bounds, int paddingleft, int paddingtop) {
        android.graphics.bitmap.config bitmapconfig = bitmap.getconfig();

        paint.setdither(true); // 获取跟清晰的图像采样
        paint.setfilterbitmap(true);// 过滤一些
        if (bitmapconfig == null) {
            bitmapconfig = android.graphics.bitmap.config.argb_8888;
        }
        bitmap = bitmap.copy(bitmapconfig, true);
        canvas canvas = new canvas(bitmap);
        canvas.drawtext(text, paddingleft, paddingtop, paint);
        return bitmap;
    }


    public static bitmap setimgsize(bitmap bm, int newwidth, int newheight) {
        // 获得图片的宽高.
        int width = bm.getwidth();
        int height = bm.getheight();
        // 计算缩放比例.
        float scalewidth = ((float) newwidth) / width;
        float scaleheight = ((float) newheight) / height;
        // 取得想要缩放的matrix参数.
        matrix matrix = new matrix();
        matrix.postscale(scalewidth, scaleheight);
        // 得到新的图片.
        return bitmap.createbitmap(bm, 0, 0, width, height, matrix, true);
    }

    // 保存图片的回调
    public interface onsaveimgcallback {

        void onsavestart();

        void onsavesuccess();

        void onsavefail();
    }

    public static void savephototomedia(context context, file file, string filename)
            throws filenotfoundexception {
        string uristring = mediastore.images.media
                .insertimage(context.getcontentresolver(), file.getabsolutepath(), filename, null);
//        string uristring = mediastore.images.media.insertimage(context.getcontentresolver(), bitmap, null, null);
        file file1 = new file(getrealpathfromuri(uri.parse(uristring), context));
        updatephotomedia(file1, context);
    }

    //更新图库
    private static void updatephotomedia(file file, context context) {
        intent intent = new intent();
        intent.setaction(intent.action_media_scanner_scan_file);
        intent.setdata(uri.fromfile(file));
        context.sendbroadcast(intent);
    }

    //得到绝对地址
    private static string getrealpathfromuri(uri contenturi, context context) {
        string[] proj = {mediastore.images.media.data};
        cursor cursor = context.getcontentresolver().query(contenturi, proj, null, null, null);
        if (cursor == null) {
            return "";
        }
        int column_index = cursor.getcolumnindexorthrow(mediastore.images.media.data);
        cursor.movetofirst();
        string filestr = cursor.getstring(column_index);
        cursor.close();
        return filestr;
    }
}