无法在Android中将Bitmap转换为完美的Base64字符串?

时间:2013-08-01 10:48:26

标签: android base64

我正在开发一个应用程序,我需要从相机中捕获图像。捕获后,我必须将位图转换为Base64 。转换为Base64后,我必须将该字符串发送到SERVER。我正在使用以下代码执行此任务:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
base64Image = Base64.encodeToString(b,Base64.DEFAULT);

问题:当我将Base64转换为图片时,我的图像不完整。同样的结果发生在服务器上,我的图像没有完全从Base64 String重构。

请建议我的解决方案。我已经搜索了很多并获得了我正在使用的相同代码。

已编辑:请参阅以下不完整图片

enter image description here

用于捕获图像的代码:

intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, TAKE_PHOTO);

3 个答案:

答案 0 :(得分:3)

创建自己的Base64类并使用:

public class Base64
{

  private Base64()
  {
    super();
  }

  /**
   *  Encode some data and return a String.
   */
  public final static String encode(byte[] d)
  {
    if (d == null) return null;
    byte data[] = new byte[d.length+2];
    System.arraycopy(d, 0, data, 0, d.length);
    byte dest[] = new byte[(data.length/3)*4];

    // 3-byte to 4-byte conversion
    for (int sidx = 0, didx=0; sidx < d.length; sidx += 3, didx += 4)
    {
      dest[didx]   = (byte) ((data[sidx] >>> 2) & 077);
      dest[didx+1] = (byte) ((data[sidx+1] >>> 4) & 017 |
                  (data[sidx] << 4) & 077);
      dest[didx+2] = (byte) ((data[sidx+2] >>> 6) & 003 |
                  (data[sidx+1] << 2) & 077);
      dest[didx+3] = (byte) (data[sidx+2] & 077);
    }

    // 0-63 to ascii printable conversion
    for (int idx = 0; idx <dest.length; idx++)
    {
      if (dest[idx] < 26)     dest[idx] = (byte)(dest[idx] + 'A');
      else if (dest[idx] < 52)  dest[idx] = (byte)(dest[idx] + 'a' - 26);
      else if (dest[idx] < 62)  dest[idx] = (byte)(dest[idx] + '0' - 52);
      else if (dest[idx] < 63)  dest[idx] = (byte)'+';
      else            dest[idx] = (byte)'/';
    }

    // add padding
    for (int idx = dest.length-1; idx > (d.length*4)/3; idx--)
    {
      dest[idx] = (byte)'=';
    }
    return new String(dest);
  }

  /**
   * Encode a String using Base64 using the default platform encoding
   **/
  public final static String encode(String s) {
    return encode(s.getBytes());
  }

  /**
   *  Decode data and return bytes.
   */
  public final static byte[] decode(String str)
  {
    if (str == null)  return  null;
    byte data[] = str.getBytes();
    return decode(data);
  }

  /**
   *  Decode data and return bytes.  Assumes that the data passed
   *  in is ASCII text.
   */
  public final static byte[] decode(byte[] data)
  {
    int tail = data.length;
    while (data[tail-1] == '=')  tail--;
    byte dest[] = new byte[tail - data.length/4];

    // ascii printable to 0-63 conversion
    for (int idx = 0; idx <data.length; idx++)
    {
      if (data[idx] == '=')    data[idx] = 0;
      else if (data[idx] == '/') data[idx] = 63;
      else if (data[idx] == '+') data[idx] = 62;
      else if (data[idx] >= '0'  &&  data[idx] <= '9')
        data[idx] = (byte)(data[idx] - ('0' - 52));
      else if (data[idx] >= 'a'  &&  data[idx] <= 'z')
        data[idx] = (byte)(data[idx] - ('a' - 26));
      else if (data[idx] >= 'A'  &&  data[idx] <= 'Z')
        data[idx] = (byte)(data[idx] - 'A');
    }

    // 4-byte to 3-byte conversion
    int sidx, didx;
    for (sidx = 0, didx=0; didx < dest.length-2; sidx += 4, didx += 3)
    {
      dest[didx]   = (byte) ( ((data[sidx] << 2) & 255) |
              ((data[sidx+1] >>> 4) & 3) );
      dest[didx+1] = (byte) ( ((data[sidx+1] << 4) & 255) |
              ((data[sidx+2] >>> 2) & 017) );
      dest[didx+2] = (byte) ( ((data[sidx+2] << 6) & 255) |
              (data[sidx+3] & 077) );
    }
    if (didx < dest.length)
    {
      dest[didx]   = (byte) ( ((data[sidx] << 2) & 255) |
              ((data[sidx+1] >>> 4) & 3) );
    }
    if (++didx < dest.length)
    {
      dest[didx]   = (byte) ( ((data[sidx+1] << 4) & 255) |
              ((data[sidx+2] >>> 2) & 017) );
    }
    return dest;
  }

  /**
   *  A simple test that encodes and decodes the first commandline argument.
   */
  public static final void main(String[] args)
  {
    if (args.length != 1)
    {
      System.out.println("Usage: Base64 string");
      System.exit(0);
    }
    try
    {
      String e = Base64.encode(args[0].getBytes());
      String d = new String(Base64.decode(e));
      System.out.println("Input   = '" + args[0] + "'");
      System.out.println("Encoded = '" + e + "'");
      System.out.println("Decoded = '" + d + "'");
    }
    catch (Exception x)
    {
      x.printStackTrace();
    }
  }
}

首先通过以下代码将您的位图转换为byteArray:

 ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();

要使用此位图图像的调用传递字节[]:

base64Image = Base64.encode(b));

您可以通过点击浏览器中的以下行来查看它,您将看到图像。

data:image/jpeg;base64,base64Image

答案 1 :(得分:2)

好的,我解决了。问题在于将base64字符串存储在数据库中。我的专栏被声明为&#34; TEXT&#34;它会削减其他图片的部分因为字符串的长度。所以我把它改成&#34; LONGTEXT&#34;现在它完美无缺!

答案 2 :(得分:0)

  

当我将Base64转换为图像时,我得到的是不完整的图像

尝试对您的图片Bitmap执行此操作,并检查某些内容是否符合预期:

Bitmap originalBitmap = (Bitmap) data.getExtras().get("data"); //or whatever image you want
Log.d(TAG, "original bitmap byte count: " + originalBitmap.getByteCount());

ByteArrayOutputStream baos = new ByteArrayOutputStream();
originalBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
Log.d(TAG, "byte array output stream size: " + baos.size());

byte[] outputByteArray = baos.toByteArray();
Log.d(TAG, "output byte array length: " + outputByteArray.length);

String base64EncodedString = Base64.encodeToString(outputByteArray, Base64.DEFAULT);
Log.d(TAG, "base64 encoded string length: " + base64EncodedString.length());

byte[] inputByteArray = Base64.decode(base64EncodedString, Base64.DEFAULT);
Log.d(TAG, "input byte array length: " + inputByteArray.length);

ByteArrayInputStream bais = new ByteArrayInputStream(inputByteArray);
Log.d(TAG, "byte array input stream size: " + bais.available());

Bitmap decodedBitmap = BitmapFactory.decodeStream(bais);
Log.d(TAG, "decoded bitmap byte count: " + decodedBitmap.getByteCount());

Log.d(TAG, "decoded bitmap same as original bitmap? " + decodedBitmap.sameAs(originalBitmap));

如果一切正常,那么问题不在于base64编码。让我知道!