在Iphone上有兩種讀取圖片數(shù)據(jù)的簡單方法: UIImageJPEGRepresentation和UIImagePNGRepresentation. UIImageJPEGRepresentation函數(shù)需要兩個參數(shù):圖片的引用和壓縮系數(shù).而UIImagePNGRepresentation只需要圖片引用作為參數(shù).
方法一:
代碼如下:
- (UIImage*)scaleFromImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
CGSize imageSize = image.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
if (width <= newSize.width && height <= newSize.height){
return image;
}
if (width == 0 || height == 0){
return image;
}
CGFloat widthFactor = newSize.width / width;
CGFloat heightFactor = newSize.height / height;
CGFloat scaleFactor = (widthFactor
CGFloat scaledWidth = width * scaleFactor;
CGFloat scaledHeight = height * scaleFactor;
CGSize targetSize = CGSizeMake(scaledWidth,scaledHeight);
UIGraphicsBeginImageContext(targetSize);
[image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
方法二:
.h具體code
代碼如下:
#import
@interface UIImage (UIImageExt)
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size;
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;
@end
.m具體code
代碼如下:
#import "UIImageExt.h"
@implementation UIImage (UIImageExt)
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
// 創(chuàng)建一個bitmap的context
// 并把它設(shè)置成為當(dāng)前正在使用的context
UIGraphicsBeginImageContext(size);
// 繪制改變大小的圖片
[img drawInRect:CGRectMake(0, 0, size.width, size.height)];
// 從當(dāng)前context中創(chuàng)建一個改變大小后的圖片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使當(dāng)前的context出堆棧
UIGraphicsEndImageContext();
// 返回新的改變大小后的圖片
return scaledImage;
}
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
UIImage *sourc
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;
新聞熱點(diǎn)
疑難解答
圖片精選