[英]iOS - Receive Memory Warning, All Malloc's Are Freed
我正在編寫一個應用程序,該應用程序需要我存儲設備攝像頭中的像素數據並將像素與先前的視頻幀進行比較。
這是給我帶來問題的方法:
-(UIImage *)detectMotion:(CGImageRef)imageRef
{
UIImage *newImage = nil;
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
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);
// this is the problem loop
for(int i = 0; i < width * height * 4; i += 4) {
int gray = 0.216 * rawData[i] + 0.715 * rawData[i + 1] + 0.0722 * rawData[i + 2];
rawData[i] = gray;
rawData[i + 1] = gray;
rawData[i + 2] = gray;
rawData[i + 3] = 255;
int grayDelta = abs(gray - prevFrameRawData[i / 4]);
int newColor = 0;
if (sqrt(grayDelta * grayDelta * 2) >= 60) {
newColor = 255;
}
rawData[i] = newColor;
rawData[i + 1] = newColor;
rawData[i + 2] = newColor;
rawData[i + 3] = 255;
prevFrameRawData[i / 4] = gray;
}
CGImageRef newCGImage = CGBitmapContextCreateImage(context);
newImage = [UIImage imageWithCGImage:newCGImage];
CGImageRelease(newCGImage);
CGContextRelease(context);
free(rawData);
}
注意:prevFrameRawData在類的init方法中被malloc,然后在dealloc方法中被釋放。
經過一些測試后,我發現如果不向內存塊分配任何值,則不會收到警告。
我以為,當您分配一個像
rawData[i] = value
它只是覆蓋了內存中的那個點。
所有這些低級C知識對我來說都是新的,希望你們能提供幫助。
原來,我們用另一種方法創建了一個額外的CGImageRef。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.