package com.ydl.ydlcommon.utils;

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)));
    }
}
