how to convert binary data to image?

2019-02-26 21:14发布

In my android application. I got binary code from a jpeg image from the code as follows.

byte[] val = stream.toByteArray();
          BigInteger bi = new BigInteger(val);
    String s =  bi.toString(2);

This string s prints the binary value of the image. My question is how to convert this binary format into a jpeg image??

4条回答
我命由我不由天
2楼-- · 2019-02-26 21:31

I've used this code in the past:

InputStream is = (InputStream)imageContent;
d = Drawable.createFromStream(is, "src");
查看更多
萌系小妹纸
3楼-- · 2019-02-26 21:32
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
savefile(bMap,"test.jpg");

private void savefile(Bitmap bt,String file)
    {
        try {
            ContextWrapper context=this;
            FileOutputStream stream =context.openFileOutput(file, 2);
            BufferedOutputStream  objectOut = null;
              //    FileOutputStream stream =(FileOutputStream) getAssets().open("temp.txt");
                  try {
                    objectOut = new BufferedOutputStream(stream);
                     bt.compress(Bitmap.CompressFormat.PNG, 100, objectOut);
                     objectOut.flush(); 
                     objectOut.close();
                  }
                  catch (Exception e) {
                   // TODO Auto-generated catch block

                      }

             } catch (FileNotFoundException e) {
               // TODO Auto-generated catch block

                  }


    }
查看更多
做自己的国王
4楼-- · 2019-02-26 21:35
Bitmap bmp=BitmapFactory.decodeByteArray(val, 0, val.length);
ImageView img = new ImageView(this);
img.setImageBitmap(bmp);

Hope this Helps

Edit: To write in Internal Memory

FileOutputStream fout;
fout = openFileOutput("temp.jpg",Context.MODE_WORLD_WRITEABLE);    
b1.compress(CompressFormat.JPEG, 100, fout);

To write in External Memory

FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/temp.JPEG");
 bm.compress(Bitmap.CompressFormat.JPEG,90, fout);
查看更多
在下西门庆
5楼-- · 2019-02-26 21:40

I'm not really sure what you want.

  • If you want to create a Bitmap-instance directly from the stream you can use BitmapFactory and display that Bitmap in an ImageView-instance afterwards:

    Bitmap image = BitmapFactory.decodeStream(stream);
    imageView.setImageBitmap(image);
    
  • If you want to convert your string representation with radix 2 back to a binary array you can use BigInteger too:

    BigInteger bigInt = new BigInteger(s, 2);
    byte[] binaryData = bigInt.toByteArray();
    
查看更多
登录 后发表回答