ImageUtil.java 1.94 KB
Newer Older
1
package com.ydl.ydlcommon.utils;
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;
import com.yidianling.common.tools.ToastUtil;

import java.io.*;

public class ImageUtil {

    public static boolean savePicture(Context context, String base64DataStr) {

        // 去掉base64中的前缀
//        String base64Str = base64DataStr.substring(base64DataStr.indexOf(",")+1, base64DataStr.length());
        File appDir = new File(Environment.getExternalStorageDirectory(), "Camera");// 图片保存的文件夹的名称
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String imgName = System.currentTimeMillis() + ".png";
        File fileTest = new File(appDir, imgName);
        byte[] data = Base64.decode(base64DataStr, Base64.DEFAULT);

        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                data[i] += 256;//调整异常数据
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(fileTest);
            os.write(data);
            os.flush();
            os.close();

            // 通知系统刷新图库
            updateAlbum(context, fileTest);
            ToastUtil.toastShort("图片已保存至相册");
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            ToastUtil.toastShort("保存失败");
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.toastShort("保存失败");
            return false;
        }
    }


    /**
     * 通知图库更新数据
     * context
     * fileName
     * file
     */
    private static void updateAlbum(Context context, File file) {
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
    }
}