at_yasu's blog

ロード的なことを

NSImage で dpi 取得

Core Fundation を使わないとだめっぽい?

てか、NSImage での size は、縦横のピクセル数の値が返って来るみたい。dpiを無理矢理 72dpiに変換した値のを。


ソースだけとりあえず。
出元はこちら -> Sample Code

// ---------------------------------------------------------------------------------------------------------------------
- (void) setImagePath: (NSString *)path
{
    // use ImageIO to get a CGImageRef for a file at a given path
    NSURL * url = [NSURL fileURLWithPath: path];

  // create the CGImageSourceRef
    CGImageSourceRef isr = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
    
    if (isr)
    {
        // options for getting image and meta data
        // - create a 'cached' image
        // - allow float pixel data
        NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:
            (id)kCFBooleanTrue, (id)kCGImageSourceShouldCache,
            (id)kCFBooleanTrue, (id)kCGImageSourceShouldAllowFloat,
            NULL];
        
        // create image at index 0 (note that ImageIO supports multi-page TIFFs, GIFs, ...)
        CGImageRef image = CGImageSourceCreateImageAtIndex(isr, 0, (CFDictionaryRef)options);
        
        // get the meta data for the image at index 0
        NSDictionary* meta = (NSDictionary*)CGImageSourceCopyPropertiesAtIndex(isr, 0, (CFDictionaryRef)options);
        
        // keep image and meta-data
        [self setImage: image
          withMetadata: meta];
        
        CFRelease (isr);
    }
}

// ---------------------------------------------------------------------------------------------------------------------
- (void) setImage: (CGImageRef)image 
     withMetadata: (NSDictionary *)meta
{
  CGImageRetain(image);
    if (mImage)
        CGImageRelease(mImage);
  mImage = image;
  
  if (meta)
        [meta retain];
    [mMeta release];
    mMeta = meta;

    // update display
    [self setNeedsDisplay:YES];
}
// ---------------------------------------------------------------------------------------------------------------------
- (float) dpiWidth
{
  NSNumber*  val = [mMeta objectForKey:(id)kCGImagePropertyDPIWidth];
  float    dpi = [val floatValue];
  return (0 == dpi ? 72. : dpi);
}
// ---------------------------------------------------------------------------------------------------------------------
- (float) dpiHeight
{
  NSNumber*  val = [mMeta objectForKey: (id)kCGImagePropertyDPIHeight];
  float    dpi = [val floatValue];
  return (0 == dpi ? 72 : dpi);
}


しかも、縦横にdpiが決まってる。そんなのある何て知らなんだ・・・

しかし objc だと直接 CF 使えるけど、Java だとどうするんだろこれ。