Создание значков (ICNS) программно из NSImage размером 1024 * 1024
Я пытаюсь создать ICNS размером 120 * 120 из изображения 1024x1024 программно. В настоящее время я создаю NSImage, затем я создаю объекты CGImageRef с соответствующим разрешением, наконец, я сохраняю их в путь с помощью CGImageDestinationAddImage().
Я пролистал различные ссылки, одна из которых: Создание ICNS программно: "Неподдерживаемый размер изображения"
Но проблема в том, что код сгенерировал файл значка того же размера. (1024 * 1024)
Вот код:
- (void)generateIconSizeFromImage:(NSString *)path
{
//destination path
NSURL *fileURL = [NSURL fileURLWithPath:@"/Users/harjotsingh/Desktop/TestIconGenerated/test1@2x.png"];
CGImageDestinationRef dr = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypePNG , 1, NULL);
//image from path
NSImage *img = [[NSImage alloc] initWithContentsOfFile:path];
//setting its size to one of icon size
[img setSize:NSMakeSize(60,60)];
//setting its rep size to one of icon size
for (NSImageRep *rep in [img representations])[rep setSize:NSMakeSize(60,60)];
//setting the dpi, so it create 120 * 120 size icon file
NSDictionary *imageProps1x = @{
(__bridge NSString *)kCGImagePropertyDPIWidth: @144.0,
(__bridge NSString *)kCGImagePropertyDPIHeight: @144.0,
};
// Add rect size
NSRect prect = NSMakeRect(0,0,60,60);
//get image for desired size
CGImageRef generatedImage = [img CGImageForProposedRect:&prect context:[NSGraphicsContext currentContext] hints:nil];
//sadly it shows the same 1024 * 1024 size
NSLog(@"width:-- %zu && height:-- %zu",CGImageGetWidth(generatedImage),CGImageGetHeight(generatedImage));
//adding to destination folder
CGImageDestinationAddImage(dr, generatedImage, (__bridge CFDictionaryRef)(imageProps1x));
//finalize.
CGImageDestinationFinalize(dr);
CFRelease(dr); }
Изображение, используемое из входного пути, имеет размер 1024 * 1024 пикселей. "правильная спецификация для элемента размером 1024 х 1024 пикселя равна 512 точкам @ 2x. Это размер (как изображения, так и изображения) (NSSize){ 512.0, 512.0 } (точек), с повторением 1024 пикселейШиро и 1024 пикселя. " ПРИМЕЧАНИЕ: об этом позаботились, но все равно не удалось.
Дайте мне знать по любому вопросу, касающемуся моего вопроса.
Спасибо за вашу помощь.
2 ответа
Я прошел через это и сделал это с небольшими изменениями. Вот рабочий код для генерации иконки из изображения большого размера:
- (void)generateIconSizeFromImage:(NSString *)path
{
NSImage * smallImage = [[NSImage alloc] initWithContentsOfFile:path];
[smallImage setSize:NSMakeSize(120,120)];
[smallImage lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[smallImage drawInRect:CGRectMake(0, 0, 120,120)];
[smallImage unlockFocus];
//destination path
NSURL *fileURL = [NSURL fileURLWithPath:@"/Volumes/Harjot/Documents/MyProjects/Cobby Mac App/test60@2x.png"];
CGImageDestinationRef dr = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypePNG , 1, NULL);
//setting the dpi, so it create 120 * 120 size icon file
NSDictionary *imageProps1x = @{
(__bridge NSString *)kCGImagePropertyDPIWidth: @144.0,
(__bridge NSString *)kCGImagePropertyDPIHeight: @144.0,
};
//get image for desired size
CGImageRef generatedImage = [smallImage CGImageForProposedRect:NULL context:[NSGraphicsContext currentContext] hints:nil];
//now it works and generate the 120 by 120 icon
NSLog(@"width:-- %zu && height:-- %zu",CGImageGetWidth(generatedImage),CGImageGetHeight(generatedImage));
//adding to destination folder
CGImageDestinationAddImage(dr, generatedImage, (__bridge CFDictionaryRef)(imageProps1x));
//finalize.
CGImageDestinationFinalize(dr);
CFRelease(dr);
}
Наслаждаться:)
Для этого будет работать метод draw rect. вот пример кода:
[smallImage drawInRect:CGRectMake(0, 0, 120,120)]
//destination path
NSURL *fileURL = [NSURL fileURLWithPath:@“Your saving path…];
CGImageDestinationRef dr = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypePNG , 1, NULL);
//setting the dpi, so it create 120 * 120 size icon file
NSDictionary *imageProps1x = @{
(__bridge NSString *)kCGImagePropertyDPIWidth: @144.0,
(__bridge NSString *)kCGImagePropertyDPIHeight: @144.0,
};
//get image for desired size
CGImageRef generatedImage = [smallImage CGImageForProposedRect:NULL context:[NSGraphicsContext currentContext] hints:nil];
//now it works and generate the 120 by 120 icon
NSLog(@"width:-- %zu && height:-- %zu",CGImageGetWidth(generatedImage),CGImageGetHeight(generatedImage));
//adding to destination folder
CGImageDestinationAddImage(dr, generatedImage, (__bridge CFDictionaryRef)(imageProps1x));