Re: How to set dpi of an image
Re: How to set dpi of an image
- Subject: Re: How to set dpi of an image
- From: Graham Cox <email@hidden>
- Date: Fri, 22 May 2009 15:02:18 +1000
On 22/05/2009, at 2:48 PM, Mahaboob wrote:
I gone through that links and I can't figure it out how to set the
dpi.
By googling I found a function to set dpi in windows :
public RenderTargetBitmap(
int pixelWidth,
int pixelHeight,
double dpiX,
double dpiY,
PixelFormat pixelFormat
)
Is there any equivalent method?
Is it my size calculation is right?
dpi is just the ratio between an image's size and the pixels it
contains.
If it helps, here's a method from DrawKit that takes a pdf image and
returns a bitmap of it at any desired dpi. It's a category method on
an object returns a pdf representation of itself (ultimately by
calling NSView's -dataWithPDFInsideRect: method). I start with a pdf
because it can be rasterized to any dpi with maximum quality.
- (CGImageRef) CGImageWithResolution:(int) dpi hasAlpha:(BOOL)
hasAlpha relativeScale:(float) relScale
{
NSPDFImageRep* pdfRep = [NSPDFImageRep imageRepWithData:[self pdf]];
NSAssert( pdfRep != nil, @"couldn't create pdf image rep");
NSAssert( relScale > 0, @"scale factor must be greater than zero");
if( pdfRep == nil )
return nil;
// create a bitmap rep of the requisite size.
NSSize bmSize = [self drawingSize];
bmSize.width = ceil(( bmSize.width * (float)dpi * relScale ) / 72.0f );
bmSize.height = ceil(( bmSize.height * (float)dpi * relScale ) /
72.0f );
NSBitmapImageRep* bmRep;
bmRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
pixelsWide:bmSize.width
pixelsHigh:bmSize.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bytesPerRow:0
bitsPerPixel:0];
NSAssert( bmRep != nil, @"couldn't create bitmap for export");
if( bmRep == nil )
return nil;
//LogEvent_( kInfoEvent, @"size = %@, dpi = %d, rep = %@",
NSStringFromSize( bmSize ), dpi, bmRep );
NSGraphicsContext* context = [NSGraphicsContext
graphicsContextWithBitmapImageRep:bmRep];
[bmRep release];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:context];
[context setShouldAntialias:YES];
[context setImageInterpolation:NSImageInterpolationHigh];
NSRect destRect = NSZeroRect;
destRect.size = bmSize;
// if not preserving alpha, paint the background in the paper colour
if ( !hasAlpha )
{
[[self paperColour] set];
NSRectFill( destRect );
}
// draw the PDF rep into the bitmap rep.
[pdfRep drawInRect:destRect];
[NSGraphicsContext restoreGraphicsState];
CGImageRef image = CGBitmapContextCreateImage([context graphicsPort]);
return (CGImageRef)[(NSObject*)image autorelease];
}
--Graham
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden