package com.android.chmo.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import com.android.chmo.app.ChmoApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by Administrator on 2018/8/16.
 */

public class ImageUtils {

    public static void saveImage(Context context, InputStream inputStream, String name) {
       String path = ChmoApplication.getAppCacheDir(context)+ "/photo/"+ name;
        try {
            File file= new File(path);
            File dir = file.getParentFile();
            if (dir != null && !dir.exists()) {
                dir.mkdirs();
            }
            FileOutputStream fileOutputStream=new FileOutputStream(file);
            int hasRead=0;
            while((hasRead=inputStream.read())!=-1){
                fileOutputStream.write(hasRead);
            }
            fileOutputStream.close();
            inputStream.close();
        }catch (Exception e) {
        }
    }


    public static Bitmap getBitmap(Context context, String fileName) {
        if(TextUtils.isEmpty(fileName)) {
            return null;
        }
        String path = ChmoApplication.getAppCacheDir(context)+ "/photo/"+ fileName;
        try {
            File file= new File(path);
            if (!file.exists()) {
                return null;
            }
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            return bitmap;
        }catch (Exception e) {
        }catch (OutOfMemoryError e) {
            System.gc();
            System.runFinalization();
        }
        return null;
    }
}
