Compress Image in iOS 12. How Will This Code Be Updated

Compress Image in iOS 12. How will this code be updated?

Do you mean swift 4.2?
Call it like this yourImageObject.jpegData(compressionQuality: 0.5) because function changed to public func jpegData(compressionQuality: CGFloat) -> Data? For more syntax I have a repo you can take a reference with changes from swift 4. https://github.com/alexliubj/Swift-Migration-4.2

Updated:
This API change is from iOS 12, not Swift 4.2. Thanks @rmaddy for your correction.

How to compress of reduce the size of an image before uploading to Parse as PFFile? (Swift)

Yes you can use UIImageJPEGRepresentation instead of UIImagePNGRepresentation to reduce your image file size. You can just create an extension UIImage as follow:

Xcode 8.2 • Swift 3.0.2

extension UIImage {
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}

/// Returns the data for the specified image in JPEG format.
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
func jpeg(_ quality: JPEGQuality) -> Data? {
return UIImageJPEGRepresentation(self, quality.rawValue)
}
}

edit/update:

Xcode 10 Swift 4.2

extension UIImage {
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}

/// Returns the data for the specified image in JPEG format.
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
func jpeg(_ jpegQuality: JPEGQuality) -> Data? {
return jpegData(compressionQuality: jpegQuality.rawValue)
}
}

Usage:

if let imageData = image.jpeg(.lowest) {
print(imageData.count)
}

Compress UIImage

Not quite sure if you want to resize or compress or both.

Below is the code for just compression :

Use JPEG Compression in two simple steps:

1) Convert UIImage to NSData

UIImage *rainyImage =[UImage imageNamed:@"rainy.jpg"];
NSData *imgData= UIImageJPEGRepresentation(rainyImage,0.1 /*compressionQuality*/);

this is lossy compression and image size is reduced.

2) Convert back to UIImage;

UIImage *image=[UIImage imageWithData:imgData];

For scaling you can use answer provided by Matteo Gobbi. But scaling might not be a the best alternative. You would rather prefer to have a thumbnail of the actual image by compression because scaling might make look your image bad on a retina display device.

UIImageJPEGRepresentation has been replaced by instance method UIImage.jpegData(compressionQuality:)

The error is telling you that as of iOS 12 the old UIImageJPEGRepresentation function has been replaced with the new jpegData method on UIImage.

Change:

let imageData = UIImageJPEGRepresentation(image, 0.75)

to:

let imageData = image.jpegData(compressionQuality: 0.75)

Similarly, the use of UIImagePNGRepresentation has been replaced with pngData().

How do I resize the UIImage to reduce upload image size

Swift 5.4 & Xcode 13

I was not satisfied with the solutions here, which generate an image based on a given KB size, since most of them used .jpegData(compressionQuality: x). This method won't work with large images, since even with compression quality set to 0.0, the large image will remain large, e.g. a 10 MB produced by portrait mode of a newer iPhone still will be above 1 MB with compressionQuality set to 0.0.

Therefore I used some answers here and rewrote a Helper Struct which converts an image in a background que:

import UIKit

struct ImageCompressor {
static func compress(image: UIImage, maxByte: Int,
completion: @escaping (UIImage?) -> ()) {
DispatchQueue.global(qos: .userInitiated).async {
guard let currentImageSize = image.jpegData(compressionQuality: 1.0)?.count else {
return completion(nil)
}

var iterationImage: UIImage? = image
var iterationImageSize = currentImageSize
var iterationCompression: CGFloat = 1.0

while iterationImageSize > maxByte && iterationCompression > 0.01 {
let percantageDecrease = getPercantageToDecreaseTo(forDataCount: iterationImageSize)

let canvasSize = CGSize(width: image.size.width * iterationCompression,
height: image.size.height * iterationCompression)
UIGraphicsBeginImageContextWithOptions(canvasSize, false, image.scale)
defer { UIGraphicsEndImageContext() }
image.draw(in: CGRect(origin: .zero, size: canvasSize))
iterationImage = UIGraphicsGetImageFromCurrentImageContext()

guard let newImageSize = iterationImage?.jpegData(compressionQuality: 1.0)?.count else {
return completion(nil)
}
iterationImageSize = newImageSize
iterationCompression -= percantageDecrease
}
completion(iterationImage)
}
}

private static func getPercantageToDecreaseTo(forDataCount dataCount: Int) -> CGFloat {
switch dataCount {
case 0..<3000000: return 0.05
case 3000000..<10000000: return 0.1
default: return 0.2
}
}
}

Compress an image to max 1 MB:

        ImageCompressor.compress(image: image, maxByte: 1000000) { image in
guard let compressedImage = image else { return }
// Use compressedImage
}
}

image compression by size - iPhone SDK

Heres some example code that will attempt to compress an image for you so that it doesn't exceed either a max compression or maximum file size

CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 250*1024;

NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);

while ([imageData length] > maxFileSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(yourImage, compression);
}

how to compress image in iphone?

You can choose a lower quality for JPEG encoding

NSData* data = UIImageJPEGRepresentation(image, 0.8);

Something like 0.8 shouldn't be too noticeable, and should really improve file sizes.

On top of this, look into resizing the image before making the JPEG representation, using a method like this:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

Source: The simplest way to resize an UIImage?



Related Topics



Leave a reply



Submit