将位图从库中正确转换为base64

时间:2014-07-24 10:04:18

标签: android bitmap base64

我开发了一个Android应用程序,我开发了一个功能,可以从图库中拍摄照片并将其发送到我的服务器并将其作为他的个人资料图片分配给用户。

我选择了一张图片(重要:由ma相机拍摄),然后在将其发送到我的服务器之前将其转换为base64。当我得到图像并尝试显示它时我只有部分图片而不是png中的图像...我试图改变JPEG格式的压缩格式而且它最糟糕......我没有了解问题,因为2天我发疯了...请帮助:)

    private Bitmap bitmap; 



    public void chooseProfilePicture(View view) {
                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, REQUEST_CODE);
            }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            InputStream stream = null;
            if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
                try {
                    if (bitmap != null)
                        bitmap.recycle(); // recyle unused bitmaps
                    stream = getContentResolver().openInputStream(data.getData());
                    bitmap = BitmapFactory.decodeStream(stream);
                    imageView.setImageBitmap(bitmap);
// HERE THE IMAGE IS DISPLAYED 100% WELL

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null)
                        try {
                            stream.close();
                        } catch (Exception ex) {
                            Log.e("EditProfilActivity", ex.getMessage());
                        }
                }
        }

public void save(View view) {

        if (bitmap != null) {

            try {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                bitmap.recycle();
                byte[] imageBytes = byteArrayOutputStream.toByteArray();
                byteArrayOutputStream.close();
                String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
                picture = encodedImage;
// HERE WHEN I TRY TO DISPLAY THE IMAGE I HAVE ONLY A PART OF THE IMAGE
            } catch (Exception e) {
                Log.e("", e.getMessage());
            }


        }

1 个答案:

答案 0 :(得分:1)

您正在尝试显示图像表单字符串(来自编码图像文件)?

byte[] imagebyteArry = byteArrayOutputStream.toByteArray();
String imageString = encodeImage(imagebyteArry);
sendImageToserver(imageString);

............

String imageString = getImageFromserver();
byte[] imagebyteArry = decodeImage(imageString);
Search how to show image from byte[] in android?

public static String encodeImage(byte[] imageByteArray) {
    return Base64.encodeBase64URLSafeString(imageByteArray);
}

public static byte[] decodeImage(String imageDataString) {
    return Base64.decodeBase64(imageDataString);
}