在android中将base64字符串转换为PNG图像

时间:2018-04-03 10:25:50

标签: android image base64

我想将 Base64 字符串转换为ImageView的png。 我现在正在使用:

byte[] decodedString = Base64.decode(imageString, Base64.DEFAULT);
    Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
    imageView.setImageBitmap(bmp);

它完美无缺,但我想要一个png图像。 感谢。

3 个答案:

答案 0 :(得分:2)

使用此

    byte[] decodedString = Base64.decode(imageString, Base64.DEFAULT);
    // Bitmap Image
    Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

    String filename = "MyImage.png";
    File file= Environment.getExternalStorageDirectory();
    File dest = new File(file, filename);

    try {
         FileOutputStream out = new FileOutputStream(dest);
         bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
         out.flush();
         out.close();
    } catch (Exception e) {
         e.printStackTrace();
    }

AndroidManifest.xml

中的必需权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

答案 1 :(得分:0)

试试这个

FileOutputStream fos = null;
try {
if (base64ImageData != null) {
   fos = context.openFileOutput("imageName.png", Context.MODE_PRIVATE);
   byte[] decodedString = android.util.Base64.decode(base64ImageData, android.util.Base64.DEFAULT);
   fos.write(decodedString);                        
   fos.flush();
   fos.close();             
}

} catch (Exception e) {

} finally {
if (fos != null) {
    fos = null;
}
}

答案 2 :(得分:0)

试试这个

       ImageView image =(ImageView)findViewById(R.id.image);
        //encode image to base64 string
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        bitmap.compress(Bitmap.CompressFormat.png, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        //decode base64 string to image
        imageBytes = Base64.decode(imageString, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        image.setImageBitmap(decodedImage);