我正在尝试为我的应用创建图片的缩略图。我正在使用 CGImageSourceCreateThumbnailAtIndex 来完成它。我看到的一个问题是,对于选项, kCGImageSourceThumbnailMaxPixelSize 是宽度和高度的最大像素大小。
我遇到的问题是:我的图像是500w x 1000h,我想将其缩小到250w x 500h。当我使用 CGImageSourceCreateThumbnailAtIndex 时,我想指定宽度为250但是它似乎正在使我的高度为250.
如何使用它来按宽度缩小矩形图像?
谢谢!
答案 0 :(得分:1)
为kCGImageSourceCreateThumbnailWithTransform
提供的选项中的键CGImageSourceCreateThumbnailAtIndex
提供值(kCFBooleanTrue),并根据完整图像的方向和像素长宽比旋转和缩放缩略图。
这是此密钥的文档
/* Specifies whether the thumbnail should be rotated and scaled according
* to the orientation and pixel aspect ratio of the full image. The value
* of this key must be a CFBooleanRef; the default value of this key is
* kCFBooleanFalse. */
IMAGEIO_EXTERN const CFStringRef kCGImageSourceCreateThumbnailWithTransform IMAGEIO_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);
您可以修改此实现以提供所需的最大值,而不是大小
添加到UIImage以使用ImageIO调整大小的类别
的UIImage + Resizing.h
#import <UIKit/UIKit.h>
@interface UIImage (Resizing)
-(UIImage*)resizedImageWithData:(NSData*)imageData withSize:(CGSize)size;
@end
的UIImage + Resizing.m
#import "UIImage+Resizing.h"
#import <ImageIO/ImageIO.h>
@implementation UIImage (Resizing)
-(UIImage*)resizedImageWithData:(NSData*)imageSource withSize:(CGSize)size{
// Resizing Using ImageIO
CGImageSourceRef src = CGImageSourceCreateWithData((__bridge CFDataRef)imageSource, nil);
// load the image at the desired size
NSDictionary* options = @{
(id)kCGImageSourceShouldAllowFloat: (id)kCFBooleanTrue,
(id)kCGImageSourceCreateThumbnailWithTransform: (id)kCFBooleanTrue,
(id)kCGImageSourceCreateThumbnailFromImageAlways: (id)kCFBooleanTrue,
(id)kCGImageSourceThumbnailMaxPixelSize: @((int)(size.width > size.height ? size.width : size.height))
};
CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(src, 0, (__bridge CFDictionaryRef)options);
if (NULL != src)
CFRelease(src);
UIImage* scaledImage = [UIImage imageWithCGImage:imageRef];
if (NULL != imageRef)
CFRelease(imageRef);
return scaledImage;
}
@end
答案 1 :(得分:-2)
有很多方法可以调整图像大小,如果你谷歌它可以找到吨..
- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = image.CGImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
CGContextConcatCTM(context, flipVertical);
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
return newImage;
}
只需尝试使用这些链接获取更多信息http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/
而Google可能是你最好的朋友。