26

画像(カメラ/写真ライブラリ)を圧縮してサーバーに送信したいのですが。高さと幅で圧縮できることは知っていますが、画像をサイズで固定サイズ(200 KB)のみに圧縮し、元の高さと幅を維持したいと思います。JPEGRepresentationの倍率は、サイズではなく、圧縮品質のみを表します。サードパーティのライブラリを使用せずにこれを実現(固定サイズに圧縮)するにはどうすればよいですか?助けてくれてありがとう。

4

7 に答える 7

63

最大圧縮または最大ファイルサイズを超えないように画像を圧縮しようとするサンプルコードを次に示します。

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);
}
于 2012-02-29T23:29:22.843 に答える
3

これを行う1つの方法は、目的のサイズが見つかるまで、ファイルをループで再圧縮することです。最初に高さと幅を見つけ、圧縮率(画像が大きいほど圧縮率が高い)を推測し、圧縮した後、サイズを確認して、差を再度分割します。

これはあまり効率的ではないことは知っていますが、特定のサイズの画像を実現するための呼び出しは1つもないと思います。

于 2012-02-29T22:46:09.103 に答える
1

ここで、JPEGRepresentationは非常にメモリを消費します。ループで使用すると、非常にメモリを消費します。したがって、以下のコードを使用すると、ImageSizeは200KBを超えることはありません。

UIImage* newImage = [self captureView:yourUIView];


- (UIImage*)captureView:(UIView *)view {  
CGRect rect = view.bounds;
UIGraphicsBeginImageContext(rect.size);  
CGContextRef context = UIGraphicsGetCurrentContext();  

[view.layer renderInContext:context];  
UIImage* img = [UIImage alloc]init];
img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();  
NSLog(@"img=%@",img);
return img;
}
于 2012-12-12T05:33:00.537 に答える
1

私は@kgutteridgeの答えを受け取り、再帰を使用してSwift3.0の同様のソリューションを作成しました。

extension UIImage {
    static func compress(image: UIImage, maxFileSize: Int, compression: CGFloat = 1.0, maxCompression: CGFloat = 0.4) -> Data? {

        if let data = UIImageJPEGRepresentation(image, compression) {

            let bcf = ByteCountFormatter()
            bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
            bcf.countStyle = .file
            let string = bcf.string(fromByteCount: Int64(data.count))
            print("Data size is: \(string)")

            if data.count > (maxFileSize * 1024 * 1024) && (compression > maxCompression) {
                let newCompression = compression - 0.1
                let compressedData = self.compress(image: image, maxFileSize: maxFileSize, compression: newCompression, maxCompression: maxCompression)
                return compressedData
            }

            return data
        }

        return nil
    }
}
于 2017-04-12T10:41:40.750 に答える
1

スウィフト4:

extension UIImage {
    func compressTo(bytes: Int) -> UIImage {
        var compression: CGFloat = 0.9
        let maxCompression: CGFloat = 0.1
        let maxSize: Int = bytes * 1024

        var imageData = jpegData(compressionQuality: compression)!
        while imageData.count > maxSize && compression > maxCompression {
            compression -= 0.1
            imageData = jpegData(compressionQuality: compression)!
        }

        return UIImage(data: imageData)!
    }
}
于 2019-04-26T08:05:47.963 に答える
0

いくつかのテストを行った後、 画像サイズと圧縮値の関係を見つけることができました。この関係は、圧縮が1未満のすべての値に対して線形であるため、画像を常に特定の値に圧縮しようとするアルゴリズムを作成しました。

//Use 0.99 because at 1, the relationship between the compression and the file size is not linear
NSData *image = UIImageJPEGRepresentation(currentImage, 0.99);
float maxFileSize = MAX_IMAGE_SIZE * 1024;

//If the image is bigger than the max file size, try to bring it down to the max file size
if ([image length] > maxFileSize) {
    image = UIImageJPEGRepresentation(currentImage, maxFileSize/[image length]);
}
于 2015-10-22T18:30:31.390 に答える
-1
- (UIImage *)resizeImageToSize:(CGSize)targetSize
{
    UIImage *sourceImage = captureImage;
    UIImage *newImage = nil;

    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;

    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;

    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;

    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // make image center aligned
        if (widthFactor < heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor > heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }

    UIGraphicsBeginImageContext(targetSize);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if(newImage == nil)
        NSLog(@"could not scale image");

    return newImage ;
}
于 2013-11-22T06:16:04.490 に答える