1

アプリケーションのサイズを小さくするために、png 画像よりも jpg とアルファを使用します。jpg とアルファ画像をマージして png を取得することはできますが、問題は、エッジが少しシャープなアルファブリード (マット) が残っていることです。これで私を助けてください。

私が書いた以下のコードは、jpg とアルファ画像から png 画像を取得するのに役立ちます。アルファブリード(マット)を取り除くのを手伝ってください。ありがとう。

+ (UIImage*)pngImageWithJPEG:(UIImage*)jpegImage compressedAlphaFile:(UIImage*)alphaImage
{
CGRect imageRect = CGRectMake(0, 0, jpegImage.size.width, jpegImage.size.height);

//Pixel Buffer
uint32_t* piPixels = (uint32_t*)malloc(imageRect.size.width * imageRect.size.height * sizeof(uint32_t));

memset(piPixels, 0, imageRect.size.width * imageRect.size.height * sizeof(uint32_t));

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(piPixels, imageRect.size.width, imageRect.size.height, 8, sizeof(uint32_t) * imageRect.size.width, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);

//Drawing the alphaImage to the pixel buffer to seperate the alpha values
CGContextDrawImage(context, imageRect, alphaImage.CGImage);

//Buffer to store the alpha values from the alphaImage
uint8_t* piAlpha = (uint8_t*)malloc(sizeof(uint8_t) * imageRect.size.width * imageRect.size.height);

//Copying the alpha values from the alphaImage to the alpha buffer
for (uint32_t y = 0; y < imageRect.size.height; y++) 
{
    for (uint32_t x = 0; x < imageRect.size.width; x++)
    {
        uint8_t* piRGBAPixel = (uint8_t*)&piPixels[y * (uint32_t)imageRect.size.width + x];

        //alpha = 0, red = 1, green = 2, blue = 3.
        piAlpha[y * (uint32_t)imageRect.size.width + x] = piRGBAPixel[1];
    }
}

//Drawing the jpegImage in the pixel buffer.
CGContextDrawImage(context, imageRect, jpegImage.CGImage);

//Setting alpha to the jpegImage
for (uint32_t y = 0; y < imageRect.size.height; y++) 
{
    for (uint32_t x = 0; x < imageRect.size.width; x++)
    {
        uint8_t* piRGBAPixel = (uint8_t*)&piPixels[y * (uint32_t)imageRect.size.width + x];

        float fAlpha0To1 = piAlpha[y * (uint32_t)imageRect.size.width + x] / 255.0f;

        //alpha = 0, red = 1, green = 2, blue = 3.
        piRGBAPixel[0] = piAlpha[y * (uint32_t)imageRect.size.width + x];
        piRGBAPixel[1] *= fAlpha0To1;
        piRGBAPixel[2] *= fAlpha0To1;
        piRGBAPixel[3] *= fAlpha0To1;
    }
}

//Creating image from the pixel buffer
CGImageRef cgImage = CGBitmapContextCreateImage(context);

//Releasing resources
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
free(piPixels);
free(piAlpha);

//Creating the pngImage to return from the cgImage
UIImage* pngImage = [UIImage imageWithCGImage:cgImage];

//Releasing the cgImage.
CGImageRelease(cgImage);

return pngImage;
}
4

1 に答える 1

0

Premultiplied alpha colorspace は、色のにじみをより適切に処理します。次のようにソース ピクセルを前処理してみてください。

r = r*a;
g = g*a;
b = b*a;

元の値を取得するには、通常、画像を読み取った後にこれを逆にします (RGB 値をaif a> 0 で割ります) が、iOS は事前に乗算されたアルファ カラーでネイティブに動作するため、その必要さえありません。


また、別の JPG+マスクよりも小さい場合があるPNG8+Alpha形式も試してください。

于 2013-03-07T13:56:49.270 に答える