package com.mayi.fastdevelop.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 图片帮助工具
 */
public class BitmapUtil {

    /**
     * 压缩图片文件大小
     *
     * @param in      需要压缩的图片绝对路径
     * @param out     压缩后保存的文件绝对路径
     * @param format  输出格式(默认JEPG):Bitmap.CompressFormat.JEPG,Bitmap.CompressFormat.PNG,Bitmap.CompressFormat.WEBP
     * @param quality 压缩质量 0-100,越高图片质量越好
     * @return 成功true, 不成功false
     */
    public static boolean compressImageFile(String in, String out, Bitmap.CompressFormat format, int quality) {
        if (!new File(in).exists()) {
            return false;
        }
        if (format == null) {
            format = Bitmap.CompressFormat.JPEG;
        }
        if (quality < 0) {
            quality = 0;
        } else if (quality > 100) {
            quality = 100;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 1;
        Bitmap inBitmap = BitmapFactory.decodeFile(in, options);

        File of = new File(out);
        FileOutputStream fos = null;
        try {
            if (!of.exists()) {
                boolean created = of.createNewFile();
                if (!created) {
                    return false;
                }
            }
            fos = new FileOutputStream(of);
            inBitmap.compress(format, quality, fos);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inBitmap != null) {
                inBitmap.recycle();
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }


    /**
     *根据宽度对图片进行缩小，再压缩，最好保存到文件
     *
     * @param in      需要压缩的图片绝对路径
     * @param out     压缩后保存的文件绝对路径
     * @param format  输出格式(默认JEPG):Bitmap.CompressFormat.JEPG,Bitmap.CompressFormat.PNG,Bitmap.CompressFormat.WEBP
     * @param maxwidth 图片最大宽
     * @return 成功true, 不成功false
     */
    public static boolean zoomsInImageFile(String in, String out, Bitmap.CompressFormat format, int maxwidth,int quality) {
        if (!new File(in).exists()) {
            return false;
        }
        if (format == null) {
            format = Bitmap.CompressFormat.JPEG;
        }

        Bitmap inBitmap = loadBitmapFromFile(in,maxwidth);
        File of = new File(out);
        FileOutputStream fos = null;
        try {
            if (!of.exists()) {
                boolean created = of.createNewFile();
                if (!created) {
                    return false;
                }
            }
            fos = new FileOutputStream(of);
            inBitmap.compress(format, quality, fos);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inBitmap != null) {
                inBitmap.recycle();
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    private static int getinSampleSize(int bitmapHeight, int height) {
        double proportion = ArithUtil.div(bitmapHeight, height);
        if (proportion >= 2) {
            return (int) proportion;
        }
        return 2;
    }

    /**
     * 根据宽高加载图片
     *
     * @param path      图片本地地址
     * @param dstWidth  宽
     * @param dstHeight 高
     * @return
     */
    public static Bitmap loadBitmapFromFile(String path, int dstWidth, int dstHeight) {
        try {

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Config.ARGB_8888;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);

            options.inSampleSize = calcSampleSize(options, dstWidth, dstHeight);

            options.inJustDecodeBounds = false;
            options.inPurgeable = true;
            options.inInputShareable = true;
            Bitmap bm = BitmapFactory.decodeFile(path, options);

            return bm;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据宽高加载图片
     *
     * @param path      图片本地地址
     * @param dstWidth  宽
     * @param dstHeight 高
     * @param minSize   做下特殊处理，小于多少的图片，就整张加载，避免失真
     * @return
     */
    public static Bitmap loadBitmapFromFile(String path, int dstWidth, int dstHeight, int minSize) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            options.inPreferredConfig = Config.ARGB_8888;
            BitmapFactory.decodeFile(path, options);

            if (options.outWidth <= minSize && options.outHeight <= minSize) { // 做下特殊处理，小于多少的图片，就整张加载，避免失真
                options.inSampleSize = 1;
            } else {
                options.inSampleSize = calcSampleSize(options, dstWidth, dstHeight);
            }

            options.inJustDecodeBounds = false;
            options.inPurgeable = true;
            options.inInputShareable = true;
            Bitmap bm = BitmapFactory.decodeFile(path, options);

            return bm;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据宽，按比例拿到图片高度
     *
     * @param path     本地文件路径
     * @param dstWidth 宽
     * @return
     */
    public static int getScaleHeight(String path, int dstWidth) {
        int dstHeight = 0;
        try {
            if (!TextUtils.isEmpty(path) && dstWidth > 0) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(path, options);

                dstHeight = options.outHeight * dstWidth / options.outWidth;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dstHeight;
    }

    /**
     * 根据文件路径加载图片
     *
     * @param path 本地路径
     * @return bitmap
     */
    public static Bitmap loadBitmapFromFile(String path) {
        return BitmapFactory.decodeFile(path);
    }

    /**
     * 按比例加载图片，大于最大宽度的图片，等比例压缩
     *
     * @param path     本地路径
     * @param maxWidth 最大宽度
     * @return
     */
    public static Bitmap loadBitmapFromFile(String path, int maxWidth) {
        int degree = readPictureDegree(path);
        Bitmap bm;

        if (maxWidth > 0) {
            int dstHeight = BitmapUtil.getScaleHeight(path, maxWidth);
            bm = loadBitmapFromFile(path, maxWidth, dstHeight);
        } else {
            bm = loadBitmapFromFile(path);
        }
        bm = rotaingImageView(degree, bm);

        return bm;
    }

    /**
     * 根据资源ID，获取图片的Bitmap对象
     *
     * @param context 上下文
     * @param id      图片资源ID
     * @return
     */
    public static Bitmap getBitmap(Context context, int id) {
        try {
            InputStream is = context.getResources().openRawResource(id);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Config.RGB_565;
            options.inJustDecodeBounds = false;
            Bitmap btp = BitmapFactory.decodeStream(is, null, options);
            is.close();
            return btp;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 计算inSampleSize
     *
     * @param options   BitmapFactory.Options
     * @param dstWidth  缩放宽度
     * @param dstHeight 缩放高度
     * @return
     */
    public static int calcSampleSize(BitmapFactory.Options options, int dstWidth, int dstHeight) {
        int height = options.outHeight;
        int width = options.outWidth;

        int inSampleSize = 1;

        if (height > dstHeight || width > dstWidth) {
            int samplesize = Math.round((float) height / (float) dstHeight);
            inSampleSize = Math.round((float) width / (float) dstWidth);
            inSampleSize = Math.max(samplesize, inSampleSize);
        }
        return inSampleSize;
    }

    /**
     * 根据图片格式保存图片
     *
     * @param bitmap 图片的Bitmap对象
     * @param path   图片的绝对路径
     * @param format 图片格式，比如Bitmap.CompressFormat.JPEG
     * @return 图片的所在绝对路径
     */
    public static String saveBitmapToFormat(Bitmap bitmap, String path, Bitmap.CompressFormat format) {
        return saveBitmapToFormat(bitmap, path, format, 100);
    }

    /**
     * 根据图片格式保存图片
     *
     * @param bitmap  图片的Bitmap对象
     * @param path    图片的绝对路径
     * @param format  图片格式，比如Bitmap.CompressFormat.JPEG
     * @param quality 压缩资料
     * @return 图片的所在绝对路径
     */
    public static String saveBitmapToFormat(Bitmap bitmap, String path, Bitmap.CompressFormat format, int quality) {

        if (path == null || bitmap == null)
            return null;

        try {
            FileOutputStream out = new FileOutputStream(new File(path));
            if (bitmap.compress(format, quality, out)) {
                out.flush();
                out.getFD().sync();
                out.close();
            }
            return path;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean createFile(File file) {
        if (file != null && !file.exists()) {
            String absolutePath = file.getAbsolutePath();
            if (absolutePath.endsWith(File.separator)) {
                //创建文件夹
                if (!file.exists()) {//文件夹不存在
                    return file.mkdirs();
                }
            } else {
                //创建文件
                if (!file.exists()) {//文件不存在
                    if (!file.getParentFile().exists()) {
                        return file.getParentFile().mkdirs();
                    }
                }
            }
        }
        return false;
    }

    /**
     * @param bitmap
     * @param path   绝对路径
     * @return 图片的所在绝对路径
     */
    public static String saveBitmapToFormat(Bitmap bitmap, String path) {
        return saveBitmapToFormat(bitmap, path, Bitmap.CompressFormat.JPEG);

    }

    /**
     * 放大缩小图片
     *
     * @param bitmap
     * @param dstWidth
     * @param dstHeight
     * @return
     */
    public static Bitmap scaledBitmap(Bitmap bitmap, int dstWidth, int dstHeight) {
        if (bitmap == null)
            return null;
        int h = bitmap.getHeight();
        int w = bitmap.getWidth();

        if (w > h) {
            if (w > dstWidth || h > dstHeight) {
                float scaleWidth = ((float) dstWidth) / w;
                float scaleHeight = ((float) dstHeight) / h;
                float scale = Math.min(scaleWidth, scaleHeight);
                Matrix matrix = new Matrix();
                matrix.postScale(scale, scale);
                Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
                if (bitmap != newBitmap) {
                    bitmap.recycle();
                }
                return newBitmap;
            } else {
                return bitmap;
            }
        } else {
            if (w > dstWidth || h > dstHeight) {
                float scaleWidth = ((float) dstHeight) / w;
                float scaleHeight = ((float) dstWidth) / h;
                float scale = Math.min(scaleWidth, scaleHeight);
                Matrix matrix = new Matrix();
                matrix.postScale(scale, scale);
                Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
                if (bitmap != newBitmap) {
                    bitmap.recycle();
                }
                return newBitmap;
            } else {
                return bitmap;
            }
        }

    }

    /**
     * 根据图片Url 获取图片
     *
     * @param url 图片URl
     * @return bitmap
     */
    public static Bitmap getBitmapFromUrl(String url) {
        InputStream is = null;
        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                is.close();
                conn.disconnect();
                return bitmap;
            } else {
                conn.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 缩放网络图片
     *
     * @param url    图片Url
     * @param width  宽
     * @param height 高
     * @return bitmap
     */
    public static Bitmap getBitmapFromUrl(String url, int width, int height) {
        Bitmap bitmap = getBitmapFromUrl(url);
        return scaledBitmap(bitmap, width, height);
    }

    /**
     * 获取图片InputStream
     *
     * @param urlPath 网络Url
     * @return
     * @throws Exception
     */
    public static InputStream getRequest(String urlPath) throws Exception {
        URL url = new URL(urlPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        if (conn.getResponseCode() == 200) {
            return conn.getInputStream();
        }
        return null;
    }

    /**
     * 根据网络Url 获取Drawable
     *
     * @param url 网络Url
     * @return Drawable
     * @throws Exception
     */
    public static Drawable getDrawableFromUrl(String url) throws Exception {
        return Drawable.createFromStream(getRequest(url), null);
    }

    /**
     * 旋转图片
     *
     * @param b       图片对象
     * @param degrees 旋转角度
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap b, int degrees) {
        if (degrees != 0 && b != null) {
            Matrix m = new Matrix();
            m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2);
            try {
                Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
                if (b != b2) {
                    b.recycle();
                    b = b2;
                }
            } catch (OutOfMemoryError ex) {
                ex.printStackTrace();
            }
        }
        return b;
    }

    /**
     * 获取Bitmap宽高
     *
     * @param context    上下文
     * @param resourceID 图片资源文件
     * @return
     */
    public static int[] getBitmapSize(Context context, int resourceID) {
        int[] ret = new int[2];
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        opts.inDensity = Bitmap.DENSITY_NONE;
        BitmapFactory.decodeResource(context.getResources(), resourceID, opts);
        ret[0] = opts.outWidth;
        ret[1] = opts.outHeight;
        return ret;
    }

    /**
     * 获取Bitmap宽高
     *
     * @param path 图片文件
     * @return
     */
    public static int[] getBitmapSize(String path) {
        try {
            BitmapFactory.Options op = new BitmapFactory.Options();
            op.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, op);

            int h = op.outHeight;
            int w = op.outWidth;

            return new int[]{w, h};
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * byte数据转Bitmap
     *
     * @param byteArray 图片的byte数据
     * @return
     */
    public static Bitmap byteToBitmap(byte[] byteArray) {
        if (byteArray.length != 0) {
            return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
        } else {
            return null;
        }
    }

    /**
     * byte数据转Drawable
     *
     * @param byteArray 图片的byte数据
     * @return
     */
    public static Drawable byteToDrawable(byte[] byteArray) {
        ByteArrayInputStream ins = new ByteArrayInputStream(byteArray);
        return Drawable.createFromStream(ins, null);
    }

    /**
     * bitmap 转 byte
     *
     * @param bm 图片bitmap
     * @return
     */
    public static byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 将Drawable转化为Bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888 : Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 转灰度图
     *
     * @param bmpOriginal
     * @return
     */
    public static Bitmap toGrayscale(Bitmap bmpOriginal) {
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();

        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Config.RGB_565);
        Canvas c = new Canvas(bmpGrayscale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);
        return bmpGrayscale;
    }

    /**
     * 灰度的圆角图片
     *
     * @param bmpOriginal
     * @return
     */
    public static Bitmap toGrayscale(Bitmap bmpOriginal, int pixels) {
        return toRoundCorner(toGrayscale(bmpOriginal), pixels);
    }

    /**
     * 获得圆角图片的方法
     *
     * @param bitmap
     * @param pixels 一般设成14
     * @return
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /**
     * 获得带倒影的图片方法
     *
     * @param bitmap
     * @return
     */
    public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
        final int reflectionGap = 4;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);

        Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false);

        Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(bitmap, 0, 0, null);
        Paint deafalutPaint = new Paint();
        canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);

        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
                bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
        paint.setShader(shader);
        // Set the Transfer mode to be porter duff and destination in
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        // Draw a rectangle using the paint with our linear gradient
        canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);

        return bitmapWithReflection;
    }

    /**
     * (缩放)重绘图片
     *
     * @param context Activity
     * @param bitmap
     * @return
     */
    public static Bitmap reDrawBitMap(Activity context, Bitmap bitmap) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int rHeight = dm.heightPixels;
        int rWidth = dm.widthPixels;
        // float rHeight=dm.heightPixels/dm.density+0.5f;
        // float rWidth=dm.widthPixels/dm.density+0.5f;
        // int height=bitmap.getScaledHeight(dm);
        // int width = bitmap.getScaledWidth(dm);
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        float zoomScale;
        /** 方式1 **/
        // if(rWidth/rHeight>width/height){//以高为准
        // zoomScale=((float) rHeight) / height;
        // }else{
        // //if(rWidth/rHeight<width/height)//以宽为准
        // zoomScale=((float) rWidth) / width;
        // }
        /** 方式2 **/
        // if(width*1.5 >= height) {//以宽为准
        // if(width >= rWidth)
        // zoomScale = ((float) rWidth) / width;
        // else
        // zoomScale = 1.0f;
        // }else {//以高为准
        // if(height >= rHeight)
        // zoomScale = ((float) rHeight) / height;
        // else
        // zoomScale = 1.0f;
        // }
        /** 方式3 **/
        if (width >= rWidth)
            zoomScale = ((float) rWidth) / width;
        else
            zoomScale = 1.0f;
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 缩放图片动作
        matrix.postScale(zoomScale, zoomScale);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    /**
     * InputStrean 转 byte数组
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        if (inStream == null) {
            return null;
        }
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }

    /**
     * 获取图片类型
     *
     * @param file
     * @return
     */
    public static String getImageType(File file) {
        if (file == null || !file.exists()) {
            return null;
        }
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            String type = getImageType(in);
            return type;
        } catch (IOException e) {
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 获取图片类型
     *
     * @param in
     * @return
     * @see #getImageType(byte[])
     */
    public static String getImageType(InputStream in) {
        if (in == null) {
            return null;
        }
        try {
            byte[] bytes = new byte[8];
            in.read(bytes);
            return getImageType(bytes);
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 获取图片类型
     *
     * @param bytes 2~8 byte at beginning of the image file
     * @return image mimetype or null if the file is not image
     */
    public static String getImageType(byte[] bytes) {
        if (isJPEG(bytes)) {
            return "image/jpeg";
        }
        if (isGIF(bytes)) {
            return "image/gif";
        }
        if (isPNG(bytes)) {
            return "image/png";
        }
        if (isBMP(bytes)) {
            return "application/x-bmp";
        }
        return null;
    }

    /**
     * 是否是JPEG格式
     *
     * @param b
     * @return
     */
    private static boolean isJPEG(byte[] b) {
        if (b.length < 2) {
            return false;
        }
        return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8);
    }

    /**
     * 是否是GIF图片
     *
     * @param b
     * @return
     */
    private static boolean isGIF(byte[] b) {
        if (b.length < 6) {
            return false;
        }
        return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8' && (b[4] == '7' || b[4] == '9') && b[5] == 'a';
    }

    /**
     * 是否是PNG图片
     *
     * @param b
     * @return
     */
    private static boolean isPNG(byte[] b) {
        if (b.length < 8) {
            return false;
        }
        return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78 && b[3] == (byte) 71 && b[4] == (byte) 13
                && b[5] == (byte) 10 && b[6] == (byte) 26 && b[7] == (byte) 10);
    }

    /**
     * 是否是BMP图片
     *
     * @param b
     * @return
     */
    private static boolean isBMP(byte[] b) {
        if (b.length < 2) {
            return false;
        }
        return (b[0] == 0x42) && (b[1] == 0x4d);
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转图片
     *
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        //旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

}
