How to reduce the image size coming from web services? - ios

In the below shown image i am getting the images from web services and passing it to a table view but when scrolling up and down the image size was increasing and it is overlapping on labels and i had given constraints also can anyone help me how to avoid this ?

Hey you don't need to resize image.
First Set fix height width of your image view with constraints in tableview cell
Second Set imageview to aspectFit.
imageView.contentMode = UIViewContentModeScaleAspectFit;
Constraints add like this of your image view
Hope you will get success using that, if you any query regarding this , just comment will help

Using content mode to fit the image is an option but if you want to crop or resize it or compress image check the below code.
Call like let imageData = image.compressImage(rate: 0.5) and then you can provide data to write the image if needed.
func compressImage(rate: CGFloat) -> Data? {
return UIImageJPEGRepresentation(self, rate)
}
OR If you want to crop the image then,
func croppedImage(_ bound: CGRect) -> UIImage? {
guard self.size.width > bound.origin.x else {
print("X coordinate is larger than the image width")
return nil
}
guard self.size.height > bound.origin.y else {
print("Y coordinate is larger than the image height")
return nil
}
let scaledBounds: CGRect = CGRect(x: bound.x * self.scale, y: bound.y * self.scale, width: bound.w * self.scale, height: bound.h * self.scale)
let imageRef = self.cgImage?.cropping(to: scaledBounds)
let croppedImage: UIImage = UIImage(cgImage: imageRef!, scale: self.scale, orientation: UIImageOrientation.up)
return croppedImage
}
Make sure to add the above methods to UIImage Extension.

I had placed a view on table view cell and then I had placed all the elements and given constraints for view and elements in it then my problem has been reduced and working perfectly when scrolling also and is as shown in image below.
here is the layout for this screen

Related

Image isn't bound to the UIImageView

I have a UIImageView in created in Inspector that I resize in my code based on a selected image which i get from the web. However on first load of the image, it's being displayed in the images normal resolution instead of the UIImageViews newly created bounds.
Resizing the UIImageView:
fullScreenImage.bounds.size = CGSize(width: scaledWidth, height: scaledHeight)
Setting the UIImageView's image
let imageStringURL = images[indexPath.row].urls!["regular"]
let imageURL = URL(string: imageStringURL!)!
let imageData = try! Data(contentsOf: imageURL)
let image = UIImage(data: imageData)
fullScreenImage.image = image
This is how it looks when the image is first clicked on to enter "fullscreen mode"
This is how it looks the second time i click it
Not really sure why the Image isn't bounding itself within the specified UIImageView bounds
Instead of resizing the bound, you can set the UIViewContentMode property of UIImageView. This will resize the imageView image to fit inside the bounds.
fullScreenImage.contentMode = .scaleAspectFit
I found a workaround solution. I tried setting the contentMode to aspect fit, and i also tried enabling clip to bounds in the inspector, however none of them worked. So I simply looked into just resizing the UIImage itself and placing it into the UIImageView.
I found an extension in another post for a UIImage that resizes it
extension UIImage{
func resizeImage(newSize: CGSize) -> UIImage {
// Guard newSize is different
guard self.size != newSize else { return self }
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
}
If anyone knows of a better way please let me know :)

UITextView lags scrolling with added images

I've a UITextView in which I add images to, with ImagePickerController.
If there is only text in it, it is smooth, but after adding 3 or 4 images it becomes laggy on scroll within its content.
I compress the image when adding it, to it's lowest quality, but I must be doing something wrong because it still lags after the third image.
Here's the code:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let _image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
self.dismiss(animated: true, completion: nil)
// Compress the retrieved image
let compressedImage = UIImage(data: _image.lowestQualityJPEGNSData!)
//create and NSTextAttachment and add your image to it.
let attachment = NSTextAttachment()
let oldWidth = compressedImage?.size.width // scales it within the UITextView
let scaleFactor = oldWidth! / (bodyEditText.frame.size.width - 10); // adjusts the desired padding
attachment.image = UIImage(cgImage: (compressedImage?.cgImage!)!, scale: scaleFactor, orientation: .up)
//put your NSTextAttachment into and attributedString
let attString = NSAttributedString(attachment: attachment)
//add this attributed string to the current position.
bodyEditText.textStorage.insert(attString, at: bodyEditText.selectedRange.location)
}
extension UIImage {
var uncompressedPNGData: Data? { return UIImagePNGRepresentation(self) }
var highestQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 1.0) }
var highQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 0.75) }
var mediumQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 0.5) }
var lowQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 0.25) }
var lowestQualityJPEGNSData:Data? { return UIImageJPEGRepresentation(self, 0.0) }
}
What may be causing this issue and any tip how can I overpass this?
Thanks for helping
EDIT
Thanks to Duncan C I've managed to remove the whole lag and increase the performance rendering images A LOT.
By that I've replaced my imagePickerController with the following content:
let size = __CGSizeApplyAffineTransform(_image.size, CGAffineTransform.init(scaleX: 0.3, y: 0.3))
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
_image.draw(in: CGRect(origin: CGPoint.zero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let att = NSTextAttachment()
att.image = scaledImage
//put your NSTextAttachment into and attributedString
let attString = NSAttributedString(attachment: att)
//add this attributed string to the current position.
bodyEditText.textStorage.insert(attString, at: bodyEditText.selectedRange.location)
You're misusing the scale factor. That's intended for handling the 1x, 2x, and 3x scaling of normal, retina, and #3x retina images.
The way you're doing it, the system has to render the full-sized images into your bounds rectangles each time it wants to draw one. If the images are considerably bigger than the size you're displaying them, you waste a bunch of memory and processing time.
First try simply setting your image view's contentMode to .scaleAspectFit and install the original image in image view without mucking around with the scale factor. See how that performs.
If that doesn't give acceptable performance you should render your starting images into an off-screen graphics context that's the target size of your image, and install the re-rendered image into your image views. You can use UIGraphicsBeginImageContextWithOptions() or various other techniques to resize your images for display.
Take a look at this link for information on image scaling and resizing:
http://nshipster.com/image-resizing/
Its not the best practice to do that. UITextViews is meant for text not all views.
you need to make a custom UIView consisting of a 1, textview 2, UICollectionView for numerous images.
In this way you can reuse this custom view at numerous places too throughout the project

Resizing UIImage to fit table cell ImageView

I have images of the size 176 points by 176 points. I am trying to resize them so that they fit into a tableViewCell's ImageView. There are a few problems that I am coming across.
Problems
I don't know what size the image view in the tableViewCell actually is.
If I simply add the image without resizing it, it is so sharp that it looses detail:
If I use this extension on UIImage (below), then the transparent parts of the UIImage turn to black, not what I want:
extension UIImage {
func resizeImageWithBounds(bounds: CGSize) -> UIImage {
let horizontalRatio = bounds.width/size.width
let verticalRatio = bounds.height/size.height
let ratio = max(horizontalRatio, verticalRatio)
let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
draw(in: CGRect(origin: CGPoint.zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
I am looking for information on how big the UIImageView is and how to best resize an image into it. I really don't want to create another set of assets (I have a lot of images), and I don't think I should have to.
Try changing the contentMode of the cell.
cell.imageView?.contentMode = .scaleAspectFit
Or, if that doesn't work, here's how to fix the issues of your resized images turning black:
UIGraphicsBeginImageContextWithOptions(newSize, false, 0) // <-- changed opaque setting from true to false

UIImageView in UITableViewCell low resolution after resizing

I really got frustrated with auto layout and UITableViewCell stuff. I have a UITableView with dynamic heighted cells. Cells can have an image inside them. Image should fit to UIImageView's width.
Images are larger than UIImageView's size. So, after downloading the image, I resize the image and then put it inside the UIImageView. However, resizing the image with respect to UIImageView's width leads to low resolution as UIScreen's scale is greater than 1. So I tried to increase the expected size of the image after the operation (size= (scale * imageViewWidth, scale * imageViewHeight)).
However, this time, cell's height becomes 2 times bigger. What I'm trying to do is basically, while keeping UIImageView's height the same, increasing the resolution.
class ProgressImageView : UIImageView{
func setImage(imagePath:String?, placeholder:String, showProgress:Bool, showDetail:Bool){
if imagePath == nil{
self.image = UIImage(named: placeholder)
}else{
if showProgress{
self.setShowActivityIndicatorView(true)
self.setIndicatorStyle(.Gray)
}
let placeholderImage = UIImage(named: placeholder)
SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: imagePath!), options: SDWebImageOptions.RefreshCached, progress: nil, completed: { (image, error, _, _, _) in
//resize image to fit width
if error != nil{
self.image = placeholderImage
}else {
self.setImageFitWidth(image)
}
})
}
}
}
extension UIImageView{
func setImageFitWidth(image: UIImage){
let w = self.bounds.size.width //* UIScreen.mainScreen().scale
print ("ImageView size:\(self.bounds.size) scaled width:\(w)")
self.image = image.convertToWidth(w)
}
}
extension UIImage{
func convertToWidth(let width: CGFloat) -> UIImage{
print ("Old image size:\(self.size)")
let ratio = self.size.width / width
let height = self.size.height / ratio
let size = CGSizeMake(width, height)
print ("New image size:\(size)")
UIGraphicsBeginImageContext(size)
self.drawInRect(CGRectMake(0, 0, size.width, size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
As you can see in setImageFitWidth method, without UIScreen.mainScreen().scale it works just fine except the resolution and with the scale, UIImageView doubles in size. By the way, I tried all possible options of the content mode (aspect fit, aspect fill etc.) and I am using auto layout.
Result in low resolution:
Result in high resolution:
I want my screen to be just like in the first ss but with resolution of the image in second ss.
Try using UIGraphicsBeginImageContextWithOptions(size: size, opaque: YES, scale: 0)
to draw your image.
Scale 0 means the function will get the proper scale factor from the device.

Pasteboard UIImage not using scale

I am building a custom keyboard and am having trouble adding an image to the pasteboard and maintaining the appropriate scale and resolution with in the pasted image. Let me start with a screenshot of the keyboard to illustrate my trouble:
So the picture of the face in the top left of the keyboard is just a UIButton with the original photo set to the background. When the button is pressed the image is resized with the following function:
func imageResize(image:UIImage, size:CGSize)-> UIImage {
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(size, false, scale)
var context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
image.drawInRect(CGRect(origin: CGPointZero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
This function creates a UIImage the same size as the UIButton with the appropriate scale to reflect the device's screen resolution. To verify that the function is correct, I added an UIImageView filled with the scaled image. The scaled image is the image that looks misplaced near the center of the keyboard. I added the UIImageView with this function:
func addImageToBottomRight(image: UIImage) {
var tempImgView = UIImageView(image: image)
self.view.addSubview(tempImgView)
tempImgView.frame.offset(dx: 100.0, dy: 50.0)
}
I have tried a few different methods for adding the image to the pasteboard, but all seem to ignore the scale of the image and display it twice as large as opposed to displaying it at a higher resolution:
let pb = UIPasteboard.generalPasteboard()!
var pngType = UIPasteboardTypeListImage[0] as! String
var jpegType = UIPasteboardTypeListImage[2] as! String
pb.image = image
pb.setData(UIImagePNGRepresentation(image), forPasteboardType: pngType)
pb.setData(UIImageJPEGRepresentation(image, 1.0), forPasteboardType: jpegType)
All three of these methods do not work correctly and produce the same result as illustrated in the screenshot. Does anyone have any suggestions of other methods? To further clarify my goal, I would like the image in the message text box to look identical to both UIImages in the keyboard in terms of size and resolution.
Here are a few properties of the UIImage before and resize in case anyone is curious:
Starting Image Size is (750.0, 750.0)
Size to scale to is: (78.0, 78.0))
Initial Scale: 1.0
Resized Image Size is (78.0, 78.0)
Resized Image Scale: 2.0
I know this is an old post, but thought I share the work around I found for this specific case of copying images and pasting to messaging apps.The thing is, when you send a picture with such apps like iMessages, whatsapp, messenger, etc, the way they display the image is so that it aspect fits to some certain horizontal width (lets say around 260 pts for this demo).
As you can see from the diagram below, if you send 150x150 image #1x resolution in imessage, it will be stretched and displayed in the required 260 width box, making the image grainy.
But if you add an empty margin of width 185 to both the left and right sides of the image, you will end up with an image of size 520x150. Now if you send that sized image in imessage, it will have to fit it in a 260 width box, ending up cramming a 520x150 image in a 260x75 box, in a way giving you a 75x75 image at #2x resolution.
You can add a clear color margin to a UIImage with a code like this
extension UIImage {
func addMargin(withInsets inset: UIEdgeInsets) -> UIImage? {
let finalSize = CGSize(width: size.width + inset.left + inset.right, height: size.height + inset.top + inset.bottom)
let finalRect = CGRect(origin: CGPoint(x: 0, y: 0), size: finalSize)
UIGraphicsBeginImageContextWithOptions(finalSize, false, scale)
UIColor.clear.setFill()
UIGraphicsGetCurrentContext()?.fill(finalRect)
let pictureOrigin = CGPoint(x: inset.left, y: inset.top)
let pictureRect = CGRect(origin: pictureOrigin, size: size)
draw(in: pictureRect)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
defer { UIGraphicsEndImageContext() }
return finalImage
}
}

Resources