将字节数组转换为位图在java

时间:2016-04-28 23:48:46

标签: java android bitmap bytearray

我正在尝试做一些非常简单的事情,最终并非如此简单。我有一个位图图像,我必须将其转换为字节以通过套接字发送。字节数组正确发送(我已经检查过),但是当我转换回位图时,我得到了bitmap = null结果。我相信我的错误在于如何将原始位图转换为字节,或者当我尝试将字节转换回位图时。

当我调试时,我意识到如果我将我的位图转换为字节,然后将其转换回位图(不通过套接字发送),它也是空的。这是我的代码:如何将位图转换为字节,然后将字节转换回位图图像?

        // I am getting my image from ApplicationInfo and I know I am getting it because I have opened it on my computer after extracting it
        Drawable icon = context.getPackageManager().getApplicationIcon(ai);
        Log.d("tag_name", "ICON" + icon);

        BitmapDrawable bitmapIcon = (BitmapDrawable)icon;
        Log.d("tag_name", "BITMAP Drawable" + bitmapIcon);

        // STREAM IMAGE DATA TO FILE
        // This is how I know I am correctly getting my png image (no errors here)

        FileOutputStream fosIcon = context.openFileOutput(applicationName + ".png", Context.MODE_PRIVATE);

        bitmapIcon.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, fosIcon);
        InputStream inputStream = context.openFileInput(applicationName + ".png");

        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        Log.d("tag_name", "BITMAP NAME" + bitmap);


        // get bitmap image in bytes to send

        int bytes = bitmap.getByteCount();
        Log.d("tag_name", "Number of Bytes" + bytes);

        ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
        bitmap.copyPixelsToBuffer(buffer); //Move the byte data to the buffer

        byte[] array = buffer.array();
        Log.d("tag_name", "array" + array);
        int start=0;
        int len=array.length;
        Log.d("tag_name", "length" + len);

        if (len < 0)
            throw new IllegalArgumentException("Negative length not allowed");
        if (start < 0 || start >= array.length)
            throw new IndexOutOfBoundsException("Out of bounds: " + start);


        // Convert BACK TO bitmap (this will be done on the other side of my socket, but it is also null here???
        Bitmap bitmap_2 = BitmapFactory.decodeByteArray(array , 0, array.length);
        System.out.println("Bitmap Name 2" + bitmap_2);

        // Open SendToClient Class to send string and image over socket

        new SendToClient(array, applicationName, len, start, packagename).execute();

1 个答案:

答案 0 :(得分:1)

我搜索了互联网,最后发现有人遇到同样的问题,其中位图返回null,以下是如何修复它!出于某种原因,它首先将字节数组转换为jpeg,然后转换为位图:

// Convert data to jpeg first then to bitmap (cant convert byte array directly to bitmap)
              YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, 100, 100, null);
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              yuvimage.compressToJpeg(new Rect(0, 0, 100, 100), 80, baos);
              byte[] jdata = baos.toByteArray();

              // Convert to Bitmap
              Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
              System.out.println("Bitmap Name 3" + bmp);

我在我创建字节数组的地方添加了这段代码。所以这里我称之为“数据”的变量是字节数组。