2017-01-19 2 views
0

Как SnapChat изменяет размер изображений в такие небольшие размеры файлов, сохраняя при этом достойное качество? Мои снимки сохраняются примерно на 90 КБ для задней камеры и 45 КБ для передней камеры. Я читал онлайн, что отправка одной привязки составляет около 15 КБ. Как лучше оптимизировать изображения?Каким образом snapchat изменяет размер изображений?

Вот мой код, который делает снимок, и изменение размера оптимизирует его для размещения:

// Takes a still image of a video, then resizes image while user is deciding whether to post or retake it 
@IBAction func takePictureButton(_ sender: Any) { 

    if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo){ 
     videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait 
     stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { 
      (sampleBuffer, error) in 

      if sampleBuffer != nil { 

       self.takePicture.isHidden = true 
       self.rotate.isHidden = true 
       self.back.isHidden = true 
       self.save.isHidden = false 
       self.retake.isHidden = false 

       let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) 
       let dataProvider = CGDataProvider(data: imageData as! CFData) 
       let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) 

       // Handles scaling image while user decides whether or not to post or retake 
       // Scale this up for smaller images.. idk why 
       let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right) 
       let size = image.size.applying(CGAffineTransform(scaleX: 0.4, y: 0.4)) 

       UIGraphicsBeginImageContextWithOptions(size, true, 0.0) 
       image.draw(in: CGRect(origin: .zero, size: size)) 

       let scaledImage = UIGraphicsGetImageFromCurrentImageContext() 
       UIGraphicsEndImageContext() 

       self.imageDataToSend = UIImageJPEGRepresentation(scaledImage!, 0.4) 
       self.imageToUpload = image 
       self.didTakePhoto = true 
       self.tempImageView.image = image 
       self.tempImageView.isHidden = false 
       self.captureSession?.stopRunning() 
      } 
     }) 
    } 
} 

ответ

1

Вы должны найти идеальный баланс изменения размера/сжатия изображения.

К счастью, вы не первый с этой проблемой. Akshay in Built.io already made some trial and error to reach the perfect balance

- (UIImage *)compressImage:(UIImage *)image{ 
    float actualHeight = image.size.height; 
    float actualWidth = image.size.width; 
    float maxHeight = 600.0; 
    float maxWidth = 800.0; 
    float imgRatio = actualWidth/actualHeight; 
    float maxRatio = maxWidth/maxHeight; 
    float compressionQuality = 0.5;//50 percent compression 

    if (actualHeight > maxHeight || actualWidth > maxWidth) { 
     if(imgRatio < maxRatio){ 
      //adjust width according to maxHeight 
      imgRatio = maxHeight/actualHeight; 
      actualWidth = imgRatio * actualWidth; 
      actualHeight = maxHeight; 
     } 
     else if(imgRatio > maxRatio){ 
      //adjust height according to maxWidth 
      imgRatio = maxWidth/actualWidth; 
      actualHeight = imgRatio * actualHeight; 
      actualWidth = maxWidth; 
     }else{ 
      actualHeight = maxHeight; 
      actualWidth = maxWidth; 
     } 
    } 

    CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight); 
    UIGraphicsBeginImageContext(rect.size); 
    [image drawInRect:rect]; 
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 
    NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality); 
    UIGraphicsEndImageContext(); 

    return [UIImage imageWithData:imageData]; 
} 
+0

Есть ли какой-либо вариант в Swift 3, о котором вы знаете? Если нет, это нормально, я преобразую его. – Devbot10

+0

В этом суть есть что-то, но я не знаю, правильно ли это. https://gist.github.com/akshay1188/4749253#file-whatsapp-image-compression –

Смежные вопросы