EzDevInfo.com

bitmap interview questions

Top bitmap frequently asked interview questions

converting Java bitmap to byte array

  Bitmap bmp   = intent.getExtras().get("data");
  int size     = bmp.getRowBytes() * bmp.getHeight();
  ByteBuffer b = ByteBuffer.allocate(size);

  bmp.copyPixelsToBuffer(b);

  byte[] bytes = new byte[size];

  try {
     b.get(bytes, 0, bytes.length);
  } catch (BufferUnderflowException e) {
     // always happens
  }
  // do something with byte[]

When I look at the buffer after the call to copyPixelsToBuffer the bytes are all 0... The bitmap returned from the camera is immutable... but that shouldn't matter since it's doing a copy.

What could be wrong with this code?


Source: (StackOverflow)

How to set a bitmap from resource

This seems simple, i am trying to set a bitmap image but from the resources i have within the application in the drawable folder.

 bm = BitmapFactory.decodeResource(null, R.id.image);

Is this correct ?


Source: (StackOverflow)

Advertisements

Load a WPF BitmapImage from a System.Drawing.Bitmap

I have an instance of a System.Drawing.Bitmap and would like to make it available to my WPF app in the form of a System.Windows.Media.Imaging.BitmapImage.

What would be the best approach for this?


Source: (StackOverflow)

How to convert a Bitmap to Drawable in android?

How can I convert a Bitmap image to Drawable ?

Thanks, Farha


Source: (StackOverflow)

MAT (Eclipse Memory Analyzer) - how to view bitmaps from memory dump

I'm analyzing memory usage of my Android app with help of Eclipse Memory Analyzer (also known as MAT). Sometimes I can find strange instances of android.graphics.Bitmap class, utilizing big portion of heap. Problem is what I can't find source of this bitmaps, no filename, no resourceID, nothing. All information what I can find for bitmap is following: bitmap_info

There is a field mBuffer with array of image pixels, I assume. But it's in some internal Android format, not PNG.

Question: how can I view image represented by this bitmap from memory dump?


Source: (StackOverflow)

OutOfMemoryError: bitmap size exceeds VM budget :- Android [duplicate]

Possible Duplicate:
Android: Strange out of memory issue while loading an image to a Bitmap object

i am downloading images from Url and displaying them. At download time it is giving out of memory error : bitmap size exceeds VM budget. I am using drawable. Code is below:

HttpClient httpclient= new DefaultHttpClient();
HttpResponse response=(HttpResponse)httpclient.execute(httpRequest);
HttpEntity entity= response.getEntity();
BufferedHttpEntity bufHttpEntity=new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();

Bitmap bm = BitmapFactory.decodeStream(instream);
Bitmap useThisBitmap = Bitmap.createScaledBitmap(bm,bm.getWidth(),bm.getHeight(), true);
bm.recycle();
BitmapDrawable bt= new BitmapDrawable(useThisBitmap);
System.gc();

Here is the error: 05-28 14:55:47.251: ERROR/AndroidRuntime(4188): java.lang.OutOfMemoryError: bitmap size exceeds VM budget


Source: (StackOverflow)

Decoding bitmaps in Android with the right size

I decode bitmaps from the SD card using BitmapFactory.decodeFile. Sometimes the bitmaps are bigger than what the application needs or that the heap allows, so I use BitmapFactory.Options.inSampleSize to request a subsampled (smaller) bitmap.

The problem is that the platform does not enforce the exact value of inSampleSize, and I sometimes end up with a bitmap either too small, or still too big for the available memory.

From http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize:

Note: the decoder will try to fulfill this request, but the resulting bitmap may have different dimensions that precisely what has been requested. Also, powers of 2 are often faster/easier for the decoder to honor.

How should I decode bitmaps from the SD card to get a bitmap of the exact size I need while consuming as little memory as possible to decode it?

Edit:

Current source code:

BitmapFactory.Options bounds = new BitmapFactory.Options();
this.bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, bounds);
if (bounds.outWidth == -1) { // TODO: Error }
int width = bounds.outWidth;
int height = bounds.outHeight;
boolean withinBounds = width <= maxWidth && height <= maxHeight;
if (!withinBounds) {
    int newWidth = calculateNewWidth(int width, int height);
    float sampleSizeF = (float) width / (float) newWidth;
    int sampleSize = Math.round(sampleSizeF);
    BitmapFactory.Options resample = new BitmapFactory.Options();
    resample.inSampleSize = sampleSize;
    bitmap = BitmapFactory.decodeFile(filePath, resample);
}

Source: (StackOverflow)

Remove the image from a imageview Android

I'm trying to make an ImageView that holds a gallery of images. By touching the user request to load the next image. If the next image isn't found in the server or takes time to load I need the old image to be empty.

setVisibility(View.GONE) or setVisibility(View.INVISIBLE) don't work for me because when invisible/gone I stop the onTouch() detecting (and the user is locked to current image).

How can I make the ImageView to load a empty bitmap or clear (remove) current bitmap?


Source: (StackOverflow)

Android: Bitmap recycle() how does it work?

Lets say i have loaded an image in a bitmap object like

Bitmap myBitmap = BitmapFactory.decodeFile(myFile);

Now what will happen if i load another bitmap like

myBitmap = BitmapFactory.decodeFile(myFile2);

What happens to the first myBitmap does it get Garbage Collected or do i have to manually garbage collect it before loading another bitmap , eg. myBitmap.recycle()

Also is there a better way to load large images and display them one after another recycling on the way


Source: (StackOverflow)

creating an empty bitmap and drawing though canvas in android

I'd like to create an empty bitmap and set canvas to that bitmap and then draw any shape on bitmap.


Source: (StackOverflow)

BitmapFactory.decodeStream returning null when options are set

I'm having issues with BitmapFactory.decodeStream(inputStream). When using it without options, it will return an image. But when I use it with options as in .decodeStream(inputStream, null, options) it never returns Bitmaps.

What I'm trying to do is to downsample a Bitmap before I actually load it to save memory. I've read some good guides, but none using .decodeStream.

WORKS JUST FINE

URL url = new URL(sUrl);
HttpURLConnection connection  = (HttpURLConnection) url.openConnection();

InputStream is = connection.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is, null, options);

DOESN'T WORK

InputStream is = connection.getInputStream();
Bitmap img = BitmapFactory.decodeStream(is, null, options);

InputStream is = connection.getInputStream();

Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;

BitmapFactory.decodeStream(is, null, options);

Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH);

if (options.outHeight * options.outWidth * 2 >= 200*100*2){
    // Load, scaling to smallest power of 2 that'll get it <= desired dimensions
    double sampleSize = scaleByHeight
    ? options.outHeight / TARGET_HEIGHT
    : options.outWidth / TARGET_WIDTH;
    options.inSampleSize =
        (int)Math.pow(2d, Math.floor(
        Math.log(sampleSize)/Math.log(2d)));
}

// Do the actual decoding
options.inJustDecodeBounds = false;
Bitmap img = BitmapFactory.decodeStream(is, null, options);

Source: (StackOverflow)

Masking(crop) image in frame

Having a rich UI application in which I want to show image with complex shape like this

enter image description here

Now what I want is to crop my image as per Mask image, Actually image is coming dynamic and can be imported from Camera or Gallery(square or rectangle shape) and I want that image to fit in my layout frame like above

So just wondering that how do I have achieve this? Any idea /hint welcome

Background frame
enter image description here
Mask
enter image description here

Like this


Source: (StackOverflow)

Converting a view to Bitmap without displaying it in Android?

I will try to explain what exactly I need to do.

I have 3 separate screens say A,B,C. There is another screen called say HomeScreen where all the 3 screens bitmap should be displayed in Gallery view and the user can select in which view does he wants to go.

I have been able to get the Bitmaps of all the 3 screens and display it in Gallery view by placing all the code in HomeScreen Activity only. Now, this has complicated the code a lot and I will like to simplify it.

So, can I call another Activity from HomeScreen and do not display it and just get the Bitmap of that screen. For example, say I just call HomeScreen and it calls Activity A,B,C and none of the Activities from A,B,C are displayed. It just gives the Bitmap of that screen by getDrawingCache(). And then we can display those bitmaps in Gallery view in HomeScreen.

I hope I have explained the problem very clearly.

Please let me know if this is actually possible.


Source: (StackOverflow)

Image to ASCII art conversion

Prologue

This subject pops up here on SO from time to time, but is removed usually because of being a poorly written question. I saw many such questions and then silence from the OP (usual low rep) when additional info is requested. From time to time if the input is good enough for me I decide to respond with an answer and it usually gets a few up-votes per day while active but then after a few weeks the question gets removed/deleted and all starts from the beginning. So I decided to write this Q&A so I can reference such questions directly without rewriting the answer over and over again …

Another reason is also this META thread targeted at me so if you got additional input feel free to comment.

Question

How to convert bitmap image to ASCII art using C++ ?

Some constraints:

  • gray scale images
  • using mono-spaced fonts
  • keeping it simple (not using too advanced stuff for beginner level programmers)

Here is a related Wiki page ASCII art (thanks to @RogerRowland)


Source: (StackOverflow)

Android: How to rotate a bitmap on a center point

I've been looking for over a day for a solution to this problem but nothing helps, even the answers here. Documentation doesn't explain anything too.

I am simply trying to get a rotation in the direction of another object. The problem is that the bitmap is not rotated around a fixed point, but rather around the bitmaps (0,0).

Here is the code I am having troubles with:

  Matrix mtx = new Matrix();
  mtx.reset();
  mtx.preTranslate(-centerX, -centerY);
  mtx.setRotate((float)direction, -centerX, -centerY);
  mtx.postTranslate(pivotX, pivotY);
  Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, spriteWidth, spriteHeight, mtx, true);
  this.bitmap = rotatedBMP;

The weird part is, it doesn't matter how I change the values within pre/postTranslate() and the float arguments in setRotation(). Can someone please help and push me in the right direction? :)


Source: (StackOverflow)