Pregunta

¿Por qué es este código de ajuste artistImage a una imagen con 0 anchura y altura 0?

  

* NSURL artistImageURL = [NSURL URLWithString: @ " http: // userserve -ak.last.fm/serve/252/8581581.jpg "];
      NSImage * artistImage = [[NSImage alloc] initWithContentsOfURL: artistImageURL];

¿Fue útil?

Solución

NSImage hace cargar esta bien para mí, pero esa imagen en particular tiene metadatos corruptos. Su resolución de acuerdo con los datos Exif es 7.1999997999228071e-06 dpi.

NSImage respeta la información DPI en el archivo, por lo que si se intenta dibujar la imagen en su tamaño natural, que obtendrá algo 2520000070 píxeles de ancho.

Otros consejos

Como escribió Ken, el DPI está en mal estado en esta imagen. Si desea forzar NSImage para ajustar el tamaño de la imagen real (ignorando el DPI), utilice el método descrito en el http://borkware.com/quickies/one?topic=NSImage :

NSBitmapImageRep *rep = [[image representations] objectAtIndex: 0];
NSSize size = NSMakeSize([rep pixelsWide], [rep pixelsHigh]);
[image setSize: size];

Que yo sepa, NSImage's -initWithContentsOfURL: sólo funciona con direcciones URL de archivos. Tendrá que recuperar la dirección URL en primer lugar, y luego usar -initWithData:

Es más o menos garantizado que contiene .representations NSImageRep * (por supuesto no siempre NSBitmapImageRep). Para estar en un lado seguro para futuras ampliaciones se puede escribir algo como código de abajo. Y también tiene en cuenta la representación múltiple (como en algunos .icns y .tiff).

@implementation NSImage (Extension)

- (void) makePixelSized {
    NSSize max = NSZeroSize;
    for (NSObject* o in self.representations) {
        if ([o isKindOfClass: NSImageRep.class]) {
            NSImageRep* r = (NSImageRep*)o;
            if (r.pixelsWide != NSImageRepMatchesDevice && r.pixelsHigh != NSImageRepMatchesDevice) {
                max.width = MAX(max.width, r.pixelsWide);
                max.height = MAX(max.height, r.pixelsHigh);
            }
        }
    }
    if (max.width > 0 && max.height > 0) {
        self.size = max;
    }
}

@end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top