簡體   English   中英

如何水平翻轉圖像以保存翻轉相冊?

[英]How to flip image horizontally to save flipped in photo album?

我一直試圖水平翻轉UIImage圖像,以便我可以將它保存在我的相冊中,一切正常,我可以將圖像保存到相冊,但圖像雖然在我的應用程序中顯示翻轉但未保存為翻轉在相冊中。 我正在使用以下代碼來翻轉圖像:

myImage?.withHorizontallyFlippedOrientation()

注意:我沒有嘗試翻轉UIImageView ,我試圖翻轉圖像並將其保存到新的圖像變量並將圖像從該圖像變量分配給UIImageView

完整的IBAction代碼:

@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)

    }

來自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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM