Convert Bitmap to ByteArray and vice versa

风格不统一 提交于 2020-01-07 07:36:39

问题


In my android application i want to convert image ,taken from camera, to byte array and convert back to bitmap to view in a image view. I can do it easily through Bitmap.compress. But i want to do it without Bitmap.compress. The problem is that i am getting white lines (poor images every time(lines) )

                        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);

回答1:


Bitmap to byte array:

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

or

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

byte array to Bitmap:

 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);


来源:https://stackoverflow.com/questions/19702481/convert-bitmap-to-bytearray-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!