从 url 创建并设置到粘贴板时,UIImage 旋转了 90 度

UIImage is rotated 90 degrees when creating from url and set to the pasteboard

我该怎么做?

let pasteboard = UIPasteboard.general
let base64EncodedImageString = "here_base_64_string_image"
let data = Data(base64Encoded: base64EncodedImageString)
let url = data?.write(withName: "image.jpeg")
pasteboard.image = UIImage(url: url) //and now when I try to paste somewhere that image for example in imessage, it is rotated... why?

可能重要的内容:

  1. 它只发生在相机创建的图像上。
  2. 但是,如果使用完全相同的过程 (!) 为 UIActivityViewController 创建 activityItems 并尝试使用 iMessage 应用程序,那么它可以工作...为什么?有什么区别?

我对 UIImageData 使用了上面两个简单的扩展:

extension Data {
    func write(withName name: String) -> URL {
        let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(name)
        do {
            try write(to: url, options: NSData.WritingOptions.atomic)
            return url
        } catch {
            return url
        }
    }
}

extension UIImage {
    convenience init?(url: URL?) {
        guard let url = url else {
            return nil
        }
        do {
            self.init(data: try Data(contentsOf: url))
        } catch {
            return nil
        }
    }
}

在服务器 returns base64EncodedString 之前,我像这样从相机上传图像:

func imagePickerController(
    _ picker: UIImagePickerController,
    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
) {
    let image = info[.originalImage] as? UIImage
    let encodedBase64 = image?.jpegData(compressionQuality: 0.9)?.base64EncodedString() ?? ""
    //upload encodedBase64 to the server... that is all
}

我不确定,但我认为 UIPasteBoard 会将您的图像转换为 PNG 并丢弃其方向。您可以明确告诉您要添加到粘贴板的数据类型,但我不确定这是否适用于您的场景。

extension Data {
    var image: UIImage? { UIImage(data: self) }
}

设置您的粘贴板数据

UIPasteboard.general.setData(jpegData, forPasteboardType: "public.jpeg")

正在从粘贴板加载数据

if let pbImage = UIPasteboard.general.data(forPasteboardType: "public.jpeg")?.image {

}

或者在设置粘贴板图像之前重绘图像属性

extension UIImage {
    func flattened(isOpaque: Bool = true) -> UIImage? {
        if imageOrientation == .up { return self }
        UIGraphicsBeginImageContextWithOptions(size, isOpaque, scale)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

UIPasteboard.general.image = image.flattened()