[iOS]: 如何获取裁剪或调整后的 png phAsset 数据?

问题描述 投票:0回答:1

我想使用下面的代码获取 PNG phAsset 的数据,但它总是返回原始图像资源的图像数据,即使我已经裁剪了它。

PHImageRequestOptions *options = [PHImageRequestOptions new];
options.networkAccessAllowed = YES;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
options.version = PHImageRequestOptionsVersionOriginal;

[[PHImageManager defaultManager] requestImageDataAndOrientationForAsset:asset 
                                                                options:options
                                                          resultHandler:^(NSData * _Nullable imageData,
                                                                          NSString * _Nullable dataUTI,
                                                                          CGImagePropertyOrientation orientation,
                                                                          NSDictionary * _Nullable info) {
    // ....
}];

我尝试使用 PHImageRequestOptionsVersionCurrent 并获得了正确的编辑图像,但返回值会丢失图片的透明度

如何确保在获得正确的编辑版本时不会丢失图像的透明度

ios image png transparency phasset
1个回答
0
投票
if let image = UIImage(named: "YourImageName") {
let width = Int(image.size.width)
let height = Int(image.size.height)
let colorSpace = CGColorSpaceCreateDeviceRGB()
var pixelData: [UInt8] = Array(repeating: 0, count: width * height * 4)

if let context = CGContext(data: &pixelData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) {
    context.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: width, height: height))

    for y in 0..<height {
        for x in 0..<width {
            let pixelIndex = (width * y + x) * 4
            let alpha = pixelData[pixelIndex + 3]
            print("Alpha at (\(x), \(y)): \(alpha)")
        }
    }
}

}

© www.soinside.com 2019 - 2024. All rights reserved.