How to create Image from unsigned char *

后端 未结 2 1375
独厮守ぢ
独厮守ぢ 2020-12-30 16:47

I am trying to create a new Image from raw data in unsigned char *. I have the bits per pixel from the data stored. I tried converting raw data into NSData, But result image

相关标签:
2条回答
  • 2020-12-30 17:09

    Try This :-

    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    GLuint *buffer;
    //point the buffer to memory location code that here accordingly
    int backingWidth = screenBounds.size.width;
    int backingHeight =screenBounds.size.height;    
    NSInteger myDataLength = backingWidth * backingHeight * 4;
    
    
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer, myDataLength, releaseScreenshotData);
    const int bitsPerComponent = 8;
    const int bitsPerPixel = 4 * bitsPerComponent;
    const int bytesPerRow = 4 * backingWidth;
    
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
    CGImageRef imageRef = CGImageCreate(backingWidth,backingHeight, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
    CGColorSpaceRelease(colorSpaceRef);
    CGDataProviderRelease(provider);
    
     UIImage *myImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
     [uiimageviewobject setImage:myImage];
     [self addSubview:uiimageviewobject];
    
    0 讨论(0)
  • 2020-12-30 17:22

    The following code creates a UIImage instance from raw pixel data assuming you have:

    • pixelData: the raw pixel data
    • imageWidth, imageHeight: the image dimensions
    • scanWidth: the number of bytes per scanline
    • bytesPerPixel: the number of bytes used per pixel, usually 4

    The resulting UIImage is assigned to the variable uiImage.

    CGDataProviderRef provider = CGDataProviderCreateWithData(
        NULL, 
        pixelData, 
        imageHeight * scanWidth, 
        NULL);
    
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
    
    CGImageRef imageRef = CGImageCreate(imageWidth,
        imageHeight,
        8,
        bytesPerPixel * 8,
        scanWidth,
        colorSpaceRef,
        bitmapInfo,
        provider,
        NULL,
        NO,
        renderingIntent);
    
    UIImage *uiImage = [UIImage imageWithCGImage:imageRef];
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorSpaceRef);
    CGImageRelease(imageRef);
    
    0 讨论(0)
提交回复
热议问题