【问题标题】:How to flip image horizontally to save flipped in photo album?如何水平翻转图像以将翻转的图像保存在相册中?
【发布时间】:2018-10-16 12:04:04
【问题描述】:

我一直在尝试水平翻转UIImage 图像,以便将其保存在我的相册中,一切正常,我可以将图像保存到相册,但图像虽然在我的应用程序中出现翻转未在相册中另存为翻转。我正在使用以下代码来翻转图像:

myImage?.withHorizontallyFlippedOrientation()

注意:我不是要翻转UIImageView,而是要翻转图像并将其保存到一个新的图像变量中,并将该图像变量中的图像分配给UIImageView

完整的 IBA 操作代码:

@IBAction func horizontalFlipBtnPressed(_ sender: Any) {
    if myImageView.image != nil{
    let image = myImageView.image
    tempImage.append((image?.withHorizontallyFlippedOrientation())!)

    myImageView.image = tempImage.last



    }
    else{
        print ("there is no image selected")
    }
}

相册保存代码:

if myImageView.image != nil{
        var image = myImageView.image
        let imageData = image!.pngData()
        let compressedImage = UIImage(data: imageData!)
        UIImageWriteToSavedPhotosAlbum(compressedImage!, nil, nil, nil)
        let alert = UIAlertController(title: "Saved", message: "Your image has been saved!", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alert.addAction(okAction)
        self.present(alert, animated: true,completion: nil)

    }

【问题讨论】:

  • 你用什么代码保存图片?
  • 我已经在上面添加了它的代码(编辑后)。

标签: ios swift uiimage


【解决方案1】:

来自 Apple 的文档:

图像方向会影响图像数据在绘制时的显示方式。

所以这实际上不会影响图像数据。

如果您只想在图像的元数据中“翻转方向”,您可以使用.withHorizontallyFlippedOrientation(),然后只保存图像(而不是将其转换为 png 数据并返回)。

如果您真的想要翻转图像数据(像素),您需要将其绘制翻转然后保存那个图像。一种方法:

func flipImageLeftRight(_ image: UIImage) -> UIImage? {

    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
    let context = UIGraphicsGetCurrentContext()!
    context.translateBy(x: image.size.width, y: image.size.height)
    context.scaleBy(x: -image.scale, y: -image.scale)

    context.draw(image.cgImage!, in: CGRect(origin:CGPoint.zero, size: image.size))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return newImage
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2018-01-17
    • 2023-03-25
    • 2019-11-26
    • 2011-06-09
    相关资源
    最近更新 更多