Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCODE 5 iOS7 how to convert UIImage (PNG) to NSData without losing the transparent background

i have a method that receives a UIImage I convert it to NSData and make a request to post that Data, it works on iOS 6 but when i try on iOS 7, the image lose the transparent background.

this is what i have tried till now:

-(void)post:(UIImage *)firm name:
{

    int x = 350;

    NSData *imageData = UIImagePNGRepresentation(firm);
    UIImage *image=[UIImage imageWithData:imageData];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, x, 40, 50)];
    imageView.backgroundColor = [UIColor clearColor];
    imageView.image = image;


    NSData *imageData2 = [NSData dataWithData:UIImagePNGRepresentation(firm)];
    UIImage *image2=[UIImage imageWithData:imageData2];
    UIImageView *imageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(160, x, 40, 50)];
    imageView2.image = image2;

    UIImageView *imageView3 = [[UIImageView alloc]initWithFrame:CGRectMake(110, x, 40, 50)];
    imageView3.image = firm;

    UIImage * img = [UIImage imageWithData:UIImagePNGRepresentation(image)];
    UIImageView *imageView4 = [[UIImageView alloc]initWithFrame:CGRectMake(210, x, 40, 50)];
    imageView4.image = img;

    [self.view addSubview:imageView];
    [self.view addSubview:imageView2];
    [self.view addSubview:imageView3];
    [self.view addSubview:imageView4];

on the the imageView3 i'm just showing it as i get it without background (till here i get it all fine) but when i convert to NSData an then get it back to UIImage it loses the transparency,

code running on iOS 7

enter image description here

Same code running on iOS 6 and below works perfect!!

enter image description here

i have created an example os my issue on Github example

like image 733
fiigo0 Avatar asked Nov 01 '22 14:11

fiigo0


1 Answers

When I use UIImagePNGRepresentation on an image with transparency on iOS7, the transparency is preserved.

For example, using this image:

stroke

When I render that using your code, I get:

enter image description here

Perhaps there's something about the image that you started with.


The issue seems to stem from the OpenGLES code that created the image. As discussed here, it appears that you need to use

glClearColor(0.0, 0.0, 0.0, 0.0);

instead of

glClearColor(1.0, 1.0, 1.0, 0.0);

I also used the kCGImageAlphaPremultipliedLast value for CGBitmapInfo.

Doing all of that, rendered the call to CGImageCreateWithMaskingColors unnecessary, and the resulting image appears to be correctly preserves the alpha channel when you call UIImagePNGRepresentation.

like image 140
Rob Avatar answered Nov 16 '22 06:11

Rob