簡體   English   中英

AVFoundation 根據預覽縱橫比裁剪捕獲的靜止圖像

[英]AVFoundation crop captured still image according to the preview aspect ratio

我的問題與這個問題大體相似:

裁剪由 AVCaptureSession 捕獲的圖像

我有一個使用 AVFoundation 來捕獲靜止圖像的應用程序。 我的 AVCaptureVideoPreviewLayer 具有 AVLayerVideoGravityResizeAspectFill 視頻重力,因此可以從頂部和底部裁剪向用戶顯示的預覽圖片。

當用戶按下“捕獲”按鈕時,實際捕獲的圖像與顯示給用戶的預覽圖片不同。 我的問題是如何相應地裁剪捕獲的圖像?

提前致謝。

我使用了此處提供的UIImage+Resize類別和我編寫的一些新方法來完成這項工作。 我重新格式化了一些代碼以使其看起來更好並且未經測試,但它應該可以工作。 :))

- (UIImage*)cropAndResizeAspectFillWithSize:(CGSize)targetSize
                       interpolationQuality:(CGInterpolationQuality)quality {

    UIImage *outputImage = nil;
    UIImage *imageForProcessing = self;

    // crop center square (AspectFill)
    if (self.size.width != self.size.height) {
        CGFloat shorterLength = 0;
        CGPoint origin = CGPointZero;
        if (self.size.width > self.size.height) {
            origin.x = (self.size.width - self.size.height)/2;
            shorterLength = self.size.height;
        }
        else {
            origin.y = (self.size.height - self.size.width)/2;
            shorterLength = self.size.width;
        }
        imageForProcessing = [imageForProcessing normalizedImage];
        imageForProcessing = [imageForProcessing croppedImage:CGRectMake(origin.x, origin.y, shorterLength, shorterLength)];
    }
    outputImage = [imageForProcessing resizedImage:targetSize interpolationQuality:quality];
    return outputImage;
}

// fix image orientation, which may wrongly rotate the output.
- (UIImage *)normalizedImage {
    if (self.imageOrientation == UIImageOrientationUp) return self;

    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    [self drawInRect:(CGRect){0, 0, self.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return normalizedImage;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM