繁体   English   中英

如何在Objective-C中正确控制内存溢出?

[英]How to control a memory overflow correctly in Objective-C?

我正在尝试将图片的所有像素值添加到数组中。 如果图片太大,则我的应用失去了与资产的连接并崩溃了。

我如何检查内存是否在增长以停止并显示警报,因为我不知道在加载图片时可以做的最大图像大小是多少?

我的代码是:

 -(NSArray*)getRGBAFromImage:(UIImage*)image atx:(int)xp atY:(int)yp
 {
NSMutableArray *resultColor = [NSMutableArray array];
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));

NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yp) + xp * bytesPerPixel;

 //EDIT: THIS IS THE LOOP
 for (int i = 0 ; i < count ; ++i)
{
    CGFloat red   = (rawData[byteIndex]     *1) ;
    CGFloat green = (rawData[byteIndex + 1] *1) ;
    CGFloat blue  = (rawData[byteIndex + 2] *1) ;
    CGFloat alpha = (rawData[byteIndex + 3] *1) ;
    byteIndex += bytesPerPixel;

    redTotal = redTotal+red;
    greenTotal = greenTotal + green;
    blueTotal = blueTotal + blue;

    UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    [result addObject:acolor];


}    
NSLog(@"width:%i hight:%i Color:%@",width,height,[color description]);
free(rawData);
return resultColor;
 }

还是应该将其添加到队列中?

谢谢!

如果图像很大(32MB),则数组将更大,因为它是对象数组。 将有8M个UIColor颜色对象。 在64位设备中,仅指向UIColor对象的指针数组将占用64MB,然后增加UIColor对象大小的8M倍。

您需要找到另一种处理方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM