文件转为bitmap bitmap转为base64 以及bas

2022-01-07  本文已影响0人  阿狸清纯的容颜

/**

* bitmap转为base64

*

* @param bitmap

* @return

*/

public static StringbitmapToBase64(Bitmap bitmap) {

String result =null;

    ByteArrayOutputStream baos =null;

    try {

if (bitmap !=null) {

baos =new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

            baos.flush();

            baos.close();

            byte[] bitmapBytes = baos.toByteArray();

            result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);

        }

}catch (IOException e) {

e.printStackTrace();

    }finally {

try {

if (baos !=null) {

baos.flush();

                baos.close();

            }

}catch (IOException e) {

e.printStackTrace();

        }

}

return result;

}

/**

* 文件转base64字符串

* @param file

* @return

*/

public static StringfileToBase64(File file) {

String base64 =null;

    InputStream in =null;

    try {

in =new FileInputStream(file);

        byte[] bytes =new byte[in.available()];

        int length = in.read(bytes);

        base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);

    }catch (FileNotFoundException e) {

// TODO Auto-generated catch block

        e.printStackTrace();

    }catch (IOException e) {

// TODO Auto-generated catch block

        e.printStackTrace();

    }finally {

try {

if (in !=null) {

in.close();

            }

}catch (IOException e) {

// TODO Auto-generated catch block

            e.printStackTrace();

        }

}

return base64;

}

/**

* base64转为bitmap

*

* @param base64Data

* @return

*/

public static Bitmapbase64ToBitmap(String base64Data) {

byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);

    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

}

上一篇下一篇

猜你喜欢

热点阅读