【问题标题】:Convert Bitmap to ByteArray and vice versa将位图转换为字节数组,反之亦然
【发布时间】:2013-11-11 05:17:41
【问题描述】:

在我的 android 应用程序中,我想将从相机拍摄的图像转换为字节数组并转换回位图以在图像视图中查看。我可以通过 Bitmap.compress 轻松完成。但我想在没有 Bitmap.compress 的情况下做到这一点。问题是我得到了白线(每次图像都很差(线))

                        Bitmap hello;    //image coming from camera
                        ByteBuffer buffer = ByteBuffer.allocate(hello.getByteCount()); 
                        hello.copyPixelsToBuffer(buffer);
                        byte[] bytes1 = buffer.array();
                        byte [] Bits = new byte[bytes1.length*4];
                        int i;
                   for(i=0;i<bytes1.length;i++)
                {
                    Bits[i*4] =
                        Bits[i*4+1] =
                        Bits[i*4+2] = (byte) ~bytes1[i]; //Invert the source bits
                    Bits[i*4+3] = -1;//0xff, that's the alpha.
                }

                Bitmap bmimage = Bitmap.createBitmap( 360,248, Bitmap.Config.ARGB_8888);
                bmimage.copyPixelsFromBuffer(ByteBuffer.wrap(Bits));
                imageView11.setImageBitmap(bmimage);

【问题讨论】:

  • 还有什么重要的理由不使用内置方法compress 并使用您的硬编码方法?
  • 现在,避免 Bitmap.compress 的原因是什么?

标签: java android bitmap byte bytebuffer


【解决方案1】:

位图到字节数组:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageBytes = stream.toByteArray();

int bytes = bitmap.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes); 
bitmap.copyPixelsToBuffer(buffer); 
byte[] array = buffer.array();

字节数组到位图:

 InputStream inputStream = new ByteArrayInputStream(bytes);
  BitmapFactory.Options o = new BitmapFactory.Options();
  BitmapFactory.decodeStream(inputStream, null, o);

【讨论】:

  • 当我对位图做字节数组时:你显示我有​​一个空指针
【解决方案2】:
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
    byte[] b = baos.toByteArray();
    ///useing following code 
    String encoded = Base64.encodeToString(b, Base64.DEFAULT);

【讨论】:

  • 你应该更仔细地阅读问题。他说他不想使用压缩方法。
猜你喜欢
  • 2013-03-26
  • 2015-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
相关资源
最近更新 更多