web-dev-qa-db-ja.com

UIImageをトリミングするには?

ピクセルを使用して画像を処理するアプリケーションを開発していますが、その画像処理では多くの時間がかかります。したがって、UIImageをトリミングしたい(画像の中央部分のみ、つまり画像の境界部分を削除/トリミングしたい)。開発コードは、

- (NSInteger) processImage1: (UIImage*) image
{

 CGFloat width = image.size.width;
 CGFloat height = image.size.height;
 struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
 if (pixels != nil)
 {
  // Create a new bitmap
  CGContextRef context = CGBitmapContextCreate(
              (void*) pixels,
              image.size.width,
              image.size.height,
              8,
              image.size.width * 4,
              CGImageGetColorSpace(image.CGImage),
              kCGImageAlphaPremultipliedLast
              );
  if (context != NULL)
  {
   // Draw the image in the bitmap
   CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);
   NSUInteger numberOfPixels = image.size.width * image.size.height;

   NSMutableArray *numberOfPixelsArray = [[[NSMutableArray alloc] initWithCapacity:numberOfPixelsArray] autorelease];
}

UIImageの中央部分(境界外でトリミング)をどのように取るか?????????

39
Rajendra Bhole

次のようなものを試してください:

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
image = [UIImage imageWithCGImage:imageRef]; 
CGImageRelease(imageRef);

注:cropRectは、画像の中央部分がある小さな長方形です...

80
Mihir Mehta

UIImageの任意の長方形の切り抜き(つまり、サブ画像)を取得する方法を探していました。

画像の向きがUIImageOrientationUp以外の場合、私が試したソリューションのほとんどは機能しません。

例えば:

http://www.Hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/

通常、iPhoneカメラを使用する場合、UIImageOrientationLeftのような他の方向があり、上記では正しい切り取りができません。これは、UIImageに関して座標系が異なるCGImageRef/CGContextDrawImageを使用しているためです。

以下のコードはUI *メソッド(CGImageRefなし)を使用しており、上/下/左/右向きの画像でこれをテストしましたが、うまく機能しているようです。


// get sub image
- (UIImage*) getSubImageFrom: (UIImage*) img WithRect: (CGRect) rect {

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // translated rectangle for drawing sub image 
    CGRect drawRect = CGRectMake(-rect.Origin.x, -rect.Origin.y, img.size.width, img.size.height);

    // clip to the bounds of the image context
    // not strictly necessary as it will get clipped anyway?
    CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height));

    // draw image
    [img drawInRect:drawRect];

    // grab image
    UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return subImage;
}
40
M-V

たった今必要だったので、Swift 4にM-Vのコードを示します。

func imageWithImage(image: UIImage, croppedTo rect: CGRect) -> UIImage {

    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()

    let drawRect = CGRect(x: -rect.Origin.x, y: -rect.Origin.y, 
                          width: image.size.width, height: image.size.height)

    context?.clip(to: CGRect(x: 0, y: 0, 
                             width: rect.size.width, height: rect.size.height))

    image.draw(in: drawRect)

    let subImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()
    return subImage!
}
3
dasdom

UIImageViewの画像だけでなく、そのUIImage内に表示する左上オフセットも設定できれば、最終的には高速になり、Spriteアトラスからの画像作成が大幅に減ります。多分これは可能です。それは確かに多くの努力を排除します!

一方、私は自分のアプリで使用するユーティリティクラスでこれらの便利な関数を作成しました。別のUIImageの一部からUIImageを作成します。指定する標準のUIImageOrientation値を使用して、回転、スケーリング、および反転するオプションがあります。ピクセルのスケーリングは元の画像から保持されます。

私のアプリは初期化中に多くのUIImageを作成しますが、これには必ず時間がかかります。ただし、一部の画像は、特定のタブが選択されるまで必要ありません。より速いロードの外観を与えるために、起動時に生成される別のスレッドでそれらを作成し、そのタブが選択されたときに完了するまで待つことができます。

このコードは にも掲載されていますiOSで画像の一部を描画する最も効率的な方法

+ (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)aperture {
    return [ChordCalcController imageByCropping:imageToCrop toRect:aperture withOrientation:UIImageOrientationUp];
}

// Draw a full image into a crop-sized area and offset to produce a cropped, rotated image
+ (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)aperture withOrientation:(UIImageOrientation)orientation {

            // convert y coordinate to Origin bottom-left
    CGFloat orgY = aperture.Origin.y + aperture.size.height - imageToCrop.size.height,
            orgX = -aperture.Origin.x,
            scaleX = 1.0,
            scaleY = 1.0,
            rot = 0.0;
    CGSize size;

    switch (orientation) {
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            size = CGSizeMake(aperture.size.height, aperture.size.width);
            break;
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            size = aperture.size;
            break;
        default:
            assert(NO);
            return nil;
    }


    switch (orientation) {
        case UIImageOrientationRight:
            rot = 1.0 * M_PI / 2.0;
            orgY -= aperture.size.height;
            break;
        case UIImageOrientationRightMirrored:
            rot = 1.0 * M_PI / 2.0;
            scaleY = -1.0;
            break;
        case UIImageOrientationDown:
            scaleX = scaleY = -1.0;
            orgX -= aperture.size.width;
            orgY -= aperture.size.height;
            break;
        case UIImageOrientationDownMirrored:
            orgY -= aperture.size.height;
            scaleY = -1.0;
            break;
        case UIImageOrientationLeft:
            rot = 3.0 * M_PI / 2.0;
            orgX -= aperture.size.height;
            break;
        case UIImageOrientationLeftMirrored:
            rot = 3.0 * M_PI / 2.0;
            orgY -= aperture.size.height;
            orgX -= aperture.size.width;
            scaleY = -1.0;
            break;
        case UIImageOrientationUp:
            break;
        case UIImageOrientationUpMirrored:
            orgX -= aperture.size.width;
            scaleX = -1.0;
            break;
    }

    // set the draw rect to pan the image to the right spot
    CGRect drawRect = CGRectMake(orgX, orgY, imageToCrop.size.width, imageToCrop.size.height);

    // create a context for the new image
    UIGraphicsBeginImageContextWithOptions(size, NO, imageToCrop.scale);
    CGContextRef gc = UIGraphicsGetCurrentContext();

    // apply rotation and scaling
    CGContextRotateCTM(gc, rot);
    CGContextScaleCTM(gc, scaleX, scaleY);

    // draw the image to our clipped context using the offset rect
    CGContextDrawImage(gc, drawRect, imageToCrop.CGImage);

    // pull the image from our cropped context
    UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

    // pop the context to get back to the default
    UIGraphicsEndImageContext();

    // Note: this is autoreleased
    return cropped;
}
2
Scott Lahteine

関数の使用

CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));

これは別の目的で使用されるサンプルコードですが、クリップは問題ありません。

- (UIImage *)aspectFillToSize:(CGSize)size
{
    CGFloat imgAspect = self.size.width / self.size.height;
    CGFloat sizeAspect = size.width/size.height;

    CGSize scaledSize;

        if (sizeAspect > imgAspect) { // increase width, crop height
            scaledSize = CGSizeMake(size.width, size.width / imgAspect);
        } else { // increase height, crop width
            scaledSize = CGSizeMake(size.height * imgAspect, size.height);
        }
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));
    [self drawInRect:CGRectMake(0.0f, 0.0f, scaledSize.width, scaledSize.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
1
karim

ポートレートが必要な場合は、すべての写真の中央を切り取ります。

@ M-Vソリューションを使用し、cropRectを置き換えます。

CGFloat height = imageTaken.size.height;
CGFloat width = imageTaken.size.width;

CGFloat newWidth = height * 9 / 16;
CGFloat newX = abs((width - newWidth)) / 2;

CGRect cropRect = CGRectMake(newX,0, newWidth ,height);
0
benjaminhallock

アスペクト比に基づいて領域からトリミングし、外側の境界範囲に基づいてサイズにスケーリングできるようにしたいと思いました。これが私のバリエーションです:

import AVFoundation
import ImageIO

class Image {

    class func crop(image:UIImage, source:CGRect, aspect:CGSize, outputExtent:CGSize) -> UIImage {

        let sourceRect = AVMakeRectWithAspectRatioInsideRect(aspect, source)
        let targetRect = AVMakeRectWithAspectRatioInsideRect(aspect, CGRect(Origin: CGPointZero, size: outputExtent))

        let opaque = true, deviceScale:CGFloat = 0.0 // use scale of device's main screen
        UIGraphicsBeginImageContextWithOptions(targetRect.size, opaque, deviceScale)

        let scale = max(
            targetRect.size.width / sourceRect.size.width,
            targetRect.size.height / sourceRect.size.height)

        let drawRect = CGRect(Origin: -sourceRect.Origin * scale, size: image.size * scale)
        image.drawInRect(drawRect)

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage
    }
}

混乱している点がいくつかあります。切り抜きとサイズ変更の個別の懸念です。トリミングは、drawInRectに渡す四角形のOriginで処理され、スケーリングはサイズ部分で処理されます。私の場合、ソースのトリミング四角形のサイズを、同じアスペクト比の出力四角形に関連付ける必要がありました。次に、スケールファクターが出力/入力であり、これをdrawRectに適用する必要があります(drawInRectに渡されます)。

注意点の1つは、このアプローチでは、描画しているイメージがイメージコンテキストよりも大きいと想定していることです。私はこれをテストしていませんが、このコードを使用してクロッピング/ズームを処理できると思いますが、前述のスケールパラメータになるようにスケールパラメータを明示的に定義します。デフォルトでは、UIKitは画面解像度に基づいて乗数を適用します。

最後に、このUIKitアプローチはCoreGraphics/QuartzおよびCore Imageアプローチよりもレベルが高く、画像の向きの問題を処理しているようです。この投稿によると、ImageIOに次ぐ、かなり高速であることにも言及する価値があります http://nshipster.com/image-resizing/

0
Chris Conover