Composer: Scale down image that are too big for upload

This commit is contained in:
Thomas Ricouard 2023-02-23 21:21:21 +01:00
parent fa0ad34bea
commit 3cc589851f
2 changed files with 43 additions and 26 deletions

View File

@ -154,7 +154,6 @@ struct ImageFileTranseferable: Transferable {
let url: URL
lazy var data: Data? = try? Data(contentsOf: url)
lazy var compressedData: Data? = image?.jpegData(compressionQuality: 0.80)
lazy var image: UIImage? = UIImage(data: data ?? Data())
static var transferRepresentation: some TransferRepresentation {
@ -197,3 +196,12 @@ public extension URL {
}
}
}
extension UIImage {
func resized(to size: CGSize) -> UIImage {
UIGraphicsImageRenderer(size: size).image { _ in
draw(in: CGRect(origin: .zero, size: size))
}
}
}

View File

@ -572,17 +572,26 @@ public class StatusEditorViewModel: NSObject, ObservableObject {
mediasImages[index] = newContainer
do {
if let index = indexOf(container: newContainer) {
if let image = originalContainer.image,
let data = image.jpegData(compressionQuality: 0.90)
{
let uploadedMedia = try await uploadMedia(data: data, mimeType: "image/jpeg")
mediasImages[index] = .init(image: mode.isInShareExtension ? originalContainer.image : nil,
movieTransferable: nil,
gifTransferable: nil,
mediaAttachment: uploadedMedia,
error: nil)
if let uploadedMedia, uploadedMedia.url == nil {
scheduleAsyncMediaRefresh(mediaAttachement: uploadedMedia)
if let image = originalContainer.image {
let data: Data?
// Mastodon API don't support images over 5K
if image.size.height > 5000 || image.size.width > 5000 {
data = image.resized(to: .init(width: image.size.width / 4,
height: image.size.height / 4))
.jpegData(compressionQuality: 0.80)
} else {
data = image.jpegData(compressionQuality: 0.80)
}
if let data {
let uploadedMedia = try await uploadMedia(data: data, mimeType: "image/jpeg")
mediasImages[index] = .init(image: mode.isInShareExtension ? originalContainer.image : nil,
movieTransferable: nil,
gifTransferable: nil,
mediaAttachment: uploadedMedia,
error: nil)
if let uploadedMedia, uploadedMedia.url == nil {
scheduleAsyncMediaRefresh(mediaAttachement: uploadedMedia)
}
}
} else if let videoURL = await originalContainer.movieTransferable?.compressedVideoURL,
let data = try? Data(contentsOf: videoURL)