How to Prevent Noisy NSBitmapImageReps

Before

Images generated for Slider’s background and tabs contained a lot of noise – random ugly pixels throughout the images.

I was unsure why this was happening, so I asked the Cocoa-Dev mailing list.

Rob Keniger kindly replied with the following solution:

“An NSBitmapImageRep is not guaranteed to be empty when you create it and in general it’s just full of random bits. You need to clear it explicitly if you are drawing non-opaque content”

He included the following snippet that solved my problem nicely:

1
2
3
4
5
6
7
- (void) clearBitmapImageRep:(NSBitmapImageRep *)bitmap {
   unsigned char* bitmapData = [bitmap bitmapData];
   if (bitmapData != NULL)
   {
       bzero(bitmapData, [bitmap bytesPerRow] * [bitmap pixelsHigh]);
   }
}

I call it as soon as I’ve created a new NSBitmapImageRep, like so:

1
2
3
4
5
NSBitmapImageRep  *theImage = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:imageSize.width pixelsHigh:imageSize.height
                            bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
                            colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
 
[self clearBitmapImageRep:theImage];

This results in noise-free images.

After

Thanks Rob!










Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed


Scroll to top

Related posts:

  1. Tile an NSImage Within an NSBezierPath Scroll to comments Another snippet I had to write during the great Slider rebuild. I needed to be able to take an NSImage supplied by the user and tile it within an NSBezierPath defined by more user-set values. The below example uses a rounded rectangle. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 NSBitmapImageRep...
  2. Fill a Path With A Scaled Image, Ignoring Image Proportions Scroll to comments While continuing to rebuild Slider’s background image features, I was forced to rewrite the code that scales an image up/down to Slider’s portal size, ignoring the image’s original proportions. The image also had to be painted within a path, as Slider may have differently shaped corners compared to the image to be [...]...
  3. Rotate NSImage in an NSImageView As soon as I implemented this I realised how much of a pain it would be to copy out the arrow images, rotate them in an external program, then copy them back in. So I put some buttons next to the arrow image wells that allow the user to rotate the arrows within Slider itself. ...
  4. Prevent Wordpress’ .htaccess From Effecting Certain Directories This really frustrated me. To ensure my next bout of horrid frustration isn't caused by the same problem I'm documenting the solution here:...

No commentsTrackback

Comments are closed.