gpt4 book ai didi

ios - UIImage 裁剪出透明像素

转载 作者:搜寻专家 更新时间:2023-10-31 08:07:33 26 4
gpt4 key购买 nike

在使用 swift 4 从 UIImage 裁剪透明像素后,我需要帮助来创建完美清晰的图像。

I want to create image with remove transparent color, So for that ihave used below code. But it blur image with small small squarerectangles appears.

使用下面的代码

let imageCroppedBg = imgWithClearBackgroung!.cropAlpha()


//UIImage extension
extension UIImage {
func cropAlpha() -> UIImage {

let cgImage = self.cgImage!;

let width = cgImage.width
let height = cgImage.height

let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel:Int = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue

guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo),
let ptr = context.data?.assumingMemoryBound(to: UInt8.self) else {
return self
}

context.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: width, height: height))

var minX = width
var minY = height
var maxX: Int = 0
var maxY: Int = 0

for x in 1 ..< width {
for y in 1 ..< height {

let i = bytesPerRow * Int(y) + bytesPerPixel * Int(x)
let a = CGFloat(ptr[i + 3]) / 255.0

if(a>0) {
if (x < minX) { minX = x };
if (x > maxX) { maxX = x };
if (y < minY) { minY = y};
if (y > maxY) { maxY = y};
}
}
}

let rect = CGRect(x: CGFloat(minX),y: CGFloat(minY), width: CGFloat(maxX-minX), height: CGFloat(maxY-minY))
let imageScale:CGFloat = self.scale
let croppedImage = self.cgImage!.cropping(to: rect)!
let ret = UIImage(cgImage: croppedImage, scale: imageScale, orientation: self.imageOrientation)

return ret;
}
}

Output blurred & small square in small

Image with Alpha/transparent pixel

最佳答案

在这一行中检查 alpha 分量是否 > 零可能还不够:

if(a>0) {
if (x < minX) { minX = x }
if (x > maxX) { maxX = x }
if (y < minY) { minY = y }
if (y > maxY) { maxY = y }
}

也许您可以提高阈值:if(a > 0.5) 或什至更高。 if (a == 1) 将是限制,它会保证完全没有透明度。

如果您希望 imageCroppedBg 具有与 imgWithClearBackgroung 相同的大小,则设置包含 UIImageView 的内容模式 imgWithClearBackgroung.scaleAspectFit:

let imageCroppedBg = imgWithClearBackgroung.cropAlpha()
imageView.image = imageCroppedBg
imageView.contentMode = .scaleAspectFit

有关内容模式的更多信息,请查看 here .

附言:在 Swift 中,; 不需要放在行尾。

关于ios - UIImage 裁剪出透明像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51927700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com