51

How do you transform a Bitmap into an InputStream?

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

2 Answers 2

119

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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 If u know a better way, add it as an answer and mention it as comment to my answer. Future people will notice it.
This post 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.
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?
@JohnSardinha I haven't written java or developed for android for over 5 years. You might wanna ask this as another question.
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);

2 Comments

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
On the other hand, getAllocationByteCount() requires API 19.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.