51

How do you transform a Bitmap into an InputStream?

I would like to use this InputStream as input to the ETC1Util.loadTexture() function.

clever_trevor
  • 1,530
  • 2
  • 22
  • 42
tjb
  • 11,480
  • 9
  • 70
  • 91

2 Answers2

115

This might work

ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); 
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
blessanm86
  • 31,439
  • 14
  • 68
  • 79
  • 3
    It's not an ideal solution, because it causes bitmap bytes to be 2 times in memory: in bitmapdata and in bos. So it's a waste of memory. – Malachiasz Oct 29 '15 at 15:49
  • 18
    @Malachiasz If u know a better way, add it as an answer and mention it as comment to my answer. Future people will notice it. – blessanm86 Oct 29 '15 at 15:54
  • 1
    [This post](https://stackoverflow.com/a/43669060/4515489) reports that EXIF data is lost in compression, so if someone is wanting the input stream in order to read EXIF info from a bitmap in memory then another method would be needed. – jk7 Sep 06 '17 at 18:00
  • Why do you need to `compress` it? You compress it to a `PNG` but what if the image is a gif? Would it apply PNG-compression which could increase the size? What does that actually do? – John Sardinha Nov 05 '19 at 18:28
  • @JohnSardinha I haven't written java or developed for android for over 5 years. You might wanna ask this as another question. – blessanm86 Nov 05 '19 at 21:11
7

This is my way:

// Your Bitmap.
Bitmap bitmap = XXX;  

int byteSize = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(byteSize);
bitmap.copyPixelsToBuffer(byteBuffer);  

// Get the byteArray.
byte[] byteArray = byteBuffer.array();

// Get the ByteArrayInputStream.
ByteArrayInputStream bs = new ByteArrayInputStream(byteArray);
jasonnn
  • 71
  • 1
  • 4
  • 1
    A caution about using getRowBytes(), "As of KITKAT, this method should not be used to calculate the memory usage of the bitmap. Instead, see getAllocationByteCount()." - from [here](https://developer.android.com/reference/android/graphics/Bitmap.html#getRowBytes()) – jk7 Sep 06 '17 at 17:55
  • On the other hand, getAllocationByteCount() requires API 19. – jk7 Sep 06 '17 at 18:04