压缩期间图像方向丢失Swift ios

时间:2016-06-12 21:44:08

标签: ios swift compression base64 uiimageorientation

我使用以下函数创建图像的缩略图:

func scaleImage(image: UIImage, toSize newSize: CGSize) -> (UIImage) {
let newRect = CGRectIntegral(CGRectMake(0,0, newSize.width, newSize.height))
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
let context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, .High)
let flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height)
CGContextConcatCTM(context, flipVertical)
CGContextDrawImage(context, newRect, image.CGImage)
let newImage = UIImage(CGImage: CGBitmapContextCreateImage(context)!)
UIGraphicsEndImageContext()
return newImage
}

我用以下方式调用它:

let imageThumb = self.scaleImage(currImage, toSize: CGSizeMake(currImage.size.width/4, currImage.size.height/4))

然后我使用以下函数对imageThumb进行编码:

func compressImage(image:UIImage) -> NSData {
    // Reducing file size to a 10th

    var actualHeight : CGFloat = image.size.height
    var actualWidth : CGFloat = image.size.width
    let maxHeight : CGFloat = 1136.0
    let maxWidth : CGFloat = 640.0
    var imgRatio : CGFloat = actualWidth/actualHeight
    let maxRatio : CGFloat = maxWidth/maxHeight
    var compressionQuality : CGFloat = 0.5

    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;
            compressionQuality = 1;
        }
    }

    let rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    image.drawInRect(rect)
    let img = UIGraphicsGetImageFromCurrentImageContext();
    let imageData = UIImageJPEGRepresentation(img, compressionQuality);
    UIGraphicsEndImageContext();

    return imageData!;
}

最后,我将其编码为base64并将其存储在我的数据库中。然后我检索它,解码它并在ImageView中显示。问题是我以纵向模式拍摄的所有照片最终都会以横向显示。我不确定方向丢失的方向。

0 个答案:

没有答案