Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 行为怪异的图像_Objective C_Cocoa_Image_Nsimage - Fatal编程技术网

Objective c 行为怪异的图像

Objective c 行为怪异的图像,objective-c,cocoa,image,nsimage,Objective C,Cocoa,Image,Nsimage,为什么此代码将artistImage设置为0宽度和0高度的图像 NSURL*artistImageURL=[NSURL URLWithString:@”“] NSImage*artistImage=[[NSImage alloc]initWithContentsOfURL:artistImageURL] 上次我检查时,NSImage的-initWithContentsOfURL:仅适用于文件URL。您需要首先检索URL,然后使用-initWithData:NSImage确实可以为我加载此罚款,但

为什么此代码将artistImage设置为0宽度和0高度的图像

NSURL*artistImageURL=[NSURL URLWithString:@”“]
NSImage*artistImage=[[NSImage alloc]initWithContentsOfURL:artistImageURL]


上次我检查时,
NSImage的
-initWithContentsOfURL:
仅适用于文件URL。您需要首先检索URL,然后使用
-initWithData:

NSImage确实可以为我加载此罚款,但该特定映像的元数据已损坏。根据exif数据,其分辨率为7.199999799928071E-06 dpi


NSImage尊重文件中的DPI信息,因此,如果您尝试以其自然大小绘制图像,您将获得2520000070像素的图像。

正如Ken所写,此图像中的DPI混乱不堪。如果要强制NSImage设置实际图像大小(忽略DPI),请使用中描述的方法:


或多或少可以保证.representation包含NSImageRep*(当然不总是NSBitmapImageRep)。为了保证将来扩展的安全,可以编写如下代码。它还考虑了多种表示(如在某些.icns和.tiff文件中)


还值得注意的是,从主线程使用任何
-initWithContentsOfURL:
方法都不是一个好主意,因为它们会阻止主事件循环。使用异步
NSURLConnection
对象创建
NSData
对象,并在完成时通知。NSImage可以从网络加载。罗布的观点是肯定的。这通常不安全。这是对NSBitmapImageRep的不安全强制转换。例如,任意图像可能是支持PDF的,在这种情况下,pixelsWide和pixelsHigh将返回NSImageRepMatchesDevice,指示rep与分辨率无关。NSImageRepMatchesDevice==0。很高兴知道。。。但是对于标准的web图像(png、gif、jpg),这不应该发生,对吗?不,关于将使用什么类型没有承诺-这是一个纯粹的不安全类型转换。这一变化的主要原因是,如果NSBitmapImageRep被弃用,取而代之的是与CGImage更匹配的新rep子类。然后,显式实例化NSBitmapImageRep的人将为compat获得它,而不是仅仅制作这样的NSImages的人。因此,我认为将其包装在“如果”中并仅在0处的表示为NSBitmapImageRep(在99.9%的情况下应该可以工作)时调用代码应该很好,如果图像恰好具有不同的表示形式,请保持原样?如果要这样做,请不要查找NSBitmapImageRep,只需处理pixelWidth或pixelHeight为NSImageRepMatchesDevice的情况。
NSBitmapImageRep *rep = [[image representations] objectAtIndex: 0];
NSSize size = NSMakeSize([rep pixelsWide], [rep pixelsHigh]);
[image setSize: size];
@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