Android P picture and achieve Byte [] array conversion between

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Andrews development, often use the pictures into byte [] array storage or transport, then byte [] array into a picture format, to obtain images.

First, convert the picture into a byte [] array
public static byte[] bitmap2Bytes(Bitmap bitmap){
    if( null != bitmap ){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);	//注意压缩png和jpg的格式和质量
        return baos.toByteArray();
    }
    return null;
}
Second, the byte [] array is converted into bitmap
public static Bitmap bytes2Bitmap(byte[] bytes, BitmapFactory.Options opts){
    if ( null != opts ){
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,opts);
    }else{
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }
}
Third, the byte [] array into a picture file and save it
private void bytes2ImageFile(byte[] bytes) {
    try {
    	//将文件保存在路径“/storage/emulated/0/demo.jpg”
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/demo.jpg");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bytes, 0, bytes.length);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Guess you like

Origin blog.csdn.net/Sunxiaolin2016/article/details/93476049