|
在项目开发过程中,遇到一种很奇怪的现象:同一张图片,在iOS、Mac端能很正常的显示出来,但在H5、Android端却显示不出来。经过对比正常的图片与这张异常图片,发现区别在于异常图片Alpha通道一项的值为“是”,而正常能够显示出来的图片该值为“否”。查看图片简介如下:那么怎么去掉一张截图的Alpha通道呢?1. 方法一 -(void)converterNSString*)name{NSLog(@"NAME:%@",name);NSURL*url=[NSURLfileURLWithPath:name];CGImageSourceRefsource;NSImage*srcImage=[[NSImagealloc]initWithContentsOfURL:url];;NSLog(@"URL:%@",url);source=CGImageSourceCreateWithData((__bridgeCFDataRef)[srcImageTIFFRepresentation],NULL);CGImageRefimageRef=CGImageSourceCreateImageAtIndex(source,0,NULL);CGRectrect=CGRectMake(0.f,0.f,CGImageGetWidth(imageRef),CGImageGetHeight(imageRef));CGContextRefbitmapContext=CGBitmapContextCreate(NULL,rect.size.width,rect.size.height,CGImageGetBitsPerComponent(imageRef),CGImageGetBytesPerRow(imageRef),CGImageGetColorSpace(imageRef),kCGImageAlphaNoneSkipLast|kCGBitmapByteOrder32Little);CGContextDrawImage(bitmapContext,rect,imageRef);CGImageRefdecompressedImageRef=CGBitmapContextCreateImage(bitmapContext);NSImage*finalImage=[[NSImagealloc]initWithCGImage:decompressedImageRefsize:NSZeroSize];NSData*imageData=[finalImageTIFFRepresentation];NSBitmapImageRep*imageRep=[NSBitmapImageRepimageRepWithData:imageData];NSDictionary*imageProps=[NSDictionarydictionaryWithObject:[NSNumbernumberWithFloat:0.9]forKey:NSImageCompressionFactor];imageData=[imageReprepresentationUsingType:NSPNGFileTypeproperties:imageProps];[imageDatawriteToFile:nameatomically:NO];CGImageRelease(decompressedImageRef);CGContextRelease(bitmapContext);}2. 方法二 CGImageRefimageRef=[imageCGImageForProposedRect:&((CGRect){0,0,image.size.width,image.size.height})context:nilhints:nil];NSIntegerbytesPerRow=CGImageGetBytesPerRow(imageRef);NSIntegerbitsPerPixel=CGImageGetBitsPerPixel(imageRef);NSIntegerbitsPerSample=16;boolhasAlpha=NO;NSIntegersamplesPerPixel=hasAlpha4:3;///画布NSBitmapImageRep*rep=[[NSBitmapImageRepalloc]initWithBitmapDataPlanes:NULLpixelsWide:image.size.widthpixelsHigh:image.size.heightbitsPerSample:bitsPerSamplesamplesPerPixel:samplesPerPixelhasAlpha:NOisPlanar:NOcolorSpaceName:NSCalibratedRGBColorSpacebytesPerRow:bytesPerRow*(bitsPerSample/8)bitsPerPixel:bitsPerPixel*(bitsPerSample/8)];NSGraphicsContext*context=[NSGraphicsContextgraphicsContextWithBitmapImageRep:rep];[NSGraphicsContextsetCurrentContext:context];[imagedrawInRect:NSMakeRect(0,0,image.size.width,image.size.height)fromRect:NSZeroRectoperation:NSCompositingOperationCopyfraction:1.0];NSData*data=[reprepresentationUsingType:NSBitmapImageFileTypePNGproperties{}];NSImage*resultImage=[[NSImagealloc]initWithData:data];方法不一样,思路一致,可以根据自己的需求调整参数。输出结果后,再次打开图片简介查看Alpha通道值。
|
|