Browse Source

scale down share preview thumbnail more memory efficiently

cyberta 3 years ago
parent
commit
96dc049eb0
2 changed files with 26 additions and 3 deletions
  1. 3 3
      DcShare/Helper/ShareAttachment.swift
  2. 23 0
      deltachat-ios/Helper/ImageFormat.swift

+ 3 - 3
DcShare/Helper/ShareAttachment.swift

@@ -113,14 +113,14 @@ class ShareAttachment {
                 self.dcContext.logger?.debug("Unexpected data: \(type(of: data))")
                 result = nil
             }
-            if let result = result {
-                let path: String? = ImageFormat.saveImage(image: result)
+            if let result = result,
+               let path = ImageFormat.saveImage(image: result) {
                 let msg = self.dcContext.newMessage(viewType: DC_MSG_IMAGE)
                 msg.setFile(filepath: path)
                 self.messages.append(msg)
                 self.delegate?.onAttachmentChanged()
                 if self.imageThumbnail == nil {
-                    self.imageThumbnail = result.scaleDownImage(toMax: self.thumbnailSize)
+                    self.imageThumbnail = ImageFormat.scaleDownImage(NSURL(fileURLWithPath: path), toMax: self.thumbnailSize)
                     self.delegate?.onThumbnailChanged()
                 }
             }

+ 23 - 0
deltachat-ios/Helper/ImageFormat.swift

@@ -106,4 +106,27 @@ extension ImageFormat {
             return nil
         }
     }
+
+    // This scaling method is more memory efficient than UIImage.scaleDownImage(toMax: CGFloat)
+    // but requires an NSURL as parameter
+    public static func scaleDownImage(_ url: NSURL, toMax: CGFloat) -> UIImage? {
+        let imgSource = CGImageSourceCreateWithURL(url, nil)
+        guard let imageSource = imgSource else {
+            return nil
+        }
+
+        var scaledImage: CGImage?
+        let options: [NSString: Any] = [
+            // The maximum width and height in pixels of a thumbnail.
+            kCGImageSourceThumbnailMaxPixelSize: toMax,
+            kCGImageSourceCreateThumbnailFromImageAlways: true,
+            // Should include kCGImageSourceCreateThumbnailWithTransform: true in the options dictionary. Otherwise, the image result will appear rotated when an image is taken from camera in the portrait orientation.
+            kCGImageSourceCreateThumbnailWithTransform: true
+        ]
+        scaledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary)
+        if let scaledImage = scaledImage {
+            return UIImage(cgImage: scaledImage)
+        }
+        return nil
+    }
 }