2013-12-18 49 views
10

正如标题所暗示的,我试图让我的Android应用程序的用户从他的设备中选择一个图像(完成),然后我想缩小图像(完成),将图像压缩/转换为png,然后将其作为base64字符串发送到API。如何将位图转换为PNG,然后转换为Android中的base64?

所以我目前调整图像大小,像这样:

options.inSampleSize = calculateInSampleSize(options, MAX_IMAGE_DIMENSION, MAX_IMAGE_DIMENSION); 
options.inJustDecodeBounds = false; 
Bitmap bitmap = BitmapFactory.decodeFile(path, options); 

我然后有一个位图,我想转换成PNG,并从那里到Base64。我找到了一些示例代码来转换为PNG并将其存储在设备here上。

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

问题是我不想保存图像。我只是想将它作为PNG保存在内存中,然后将它进一步转换为base64字符串。

有没有人知道我可以如何将图像转换为PNG并将其存储在变量中,或者甚至更好地将其转换为base64?欢迎所有提示!

回答

19

尝试使用此方法的位图转换成PNG:

bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream); 

检查method's documentation

您可以直接将位图转换为Base64。用它来编码和解码Base64。

public static String encodeToBase64(Bitmap image) 
{ 
    Bitmap immagex=image; 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
    byte[] b = baos.toByteArray(); 
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT); 

    Log.e("LOOK", imageEncoded); 
    return imageEncoded; 
} 

public static Bitmap decodeBase64(String input) 
{ 
    byte[] decodedByte = Base64.decode(input, 0); 
    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); 
} 
相关问题