gpt4 book ai didi

iphone - 尝试在后台保存图像

转载 作者:行者123 更新时间:2023-11-29 04:13:16 26 4
gpt4 key购买 nike

我尝试在主线程以外的其他线程中调用 UIImagePNGRepresentation,但我只收到 EXC_BAD_ACCESS 异常。

这是代码

UIImage *imageToSave = [UIImage imageWithCGImage:imageRef];

dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(taskQ,
^{
NSData *binaryImage = UIImagePNGRepresentation(imageToSave);

if (![binaryImage writeToFile:destinationFilePath atomically:YES]) {
SCASSERT(assCodeCannotCreateFile, @"Write of image file failed!");
};
});

尝试访问 imageToSave 变量时发生异常。

编辑:我想将OpenGL场景保存到PNG文件,有整个功能的代码

- (void)saveImage:(NSString *)destinationFilePath {

NSUInteger width = (uint)self.frame.size.width;
NSUInteger height = (uint)self.frame.size.height;

NSUInteger myDataLength = width * height * 4;

// allocate array and read pixels into it.
GLubyte *buffer = (GLubyte *)malloc(myDataLength);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

// gl renders "upside down" so swap top to bottom into new array.
// there's gotta be a better way, but this works.
GLubyte *buffer2 = (GLubyte *)malloc(myDataLength);

for (int y = 0; y <height; y++) {
for (int x = 0; x <width * 4; x++) {
buffer2[((int)height - 1 - y) * (int)width * 4 + x] = buffer[y * 4 * (int)width + x];
}
}

JFFree(buffer);

// make data provider with data.
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);

// prep the ingredients
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * width;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

// make the cgimage
CGImageRef imageRef = CGImageCreate(width,
height,
bitsPerComponent,
bitsPerPixel,
bytesPerRow,
colorSpaceRef,
bitmapInfo,
provider,
NULL,
NO,
renderingIntent);

UIImage *imageToSave = [UIImage imageWithCGImage:imageRef];

dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(taskQ,
^{
NSData *binaryImage = UIImagePNGRepresentation(imageToSave);

if (![binaryImage writeToFile:destinationFilePath atomically:YES]) {
SCASSERT(assCodeCannotCreateFile, @"Write of image file failed!");
};
});

// release resources
CGColorSpaceRelease(colorSpaceRef);
CGDataProviderRelease(provider);
CGImageRelease(imageRef);
JFFree(buffer2);
}

最佳答案

省略 CGImageRelease 调用,因为 UIImage 不保留 CGImageRef

参见 imageWithCGImage and memory

关于iphone - 尝试在后台保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14069595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com