我有这个代码,其中self
是UIImage对象:
CGFloat scale = [sideSize floatValue] / MIN(self.size.width, self.size.height);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.size.width*scale,self.size.height*scale), NO, 0.0);
[self drawInRect:CGRectMake(0, 0, self.size.width*scale, self.size.height*scale)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
SBLog(@"%f, %f", newImage.size.width, newImage.size.height);
return newImage;
但是,当我使用函数UIImagePNGRepresentation
获取字节数据以通过互联网传输时,我会得到经过缩放后具有另一大小的图像字节。
在这段代码之后,当我使用[newImage CGImage]
时,我得到了同样的错误大小。
所以,我认为UIImagePNGRepresentation
使用CGImage从图像中获取数据字节。
那么,如何做相同的UIImage和CGImage呢?
//This method will resize the original image to desired width
//maintaining the Aspect Ratio
-(UIImage*)getResizedToWidth:(CGFloat)width
{
UIImage *resultImage = nil;
CGFloat ar = self.size.width/self.size.height;
CGFloat ht = width/ar;
CGSize newSize = CGSizeMake(width, ht);
UIGraphicsBeginImageContext(newSize);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -newSize.height);
CGRect imageRect = CGRectMake(0, 0, newSize.width, newSize.height);
CGContextDrawImage(ctx, imageRect, self.CGImage);
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
//This method will resize the original image to desired height
//maintaining the Aspect Ratio
-(UIImage*)getResizedToHeight:(CGFloat)height
{
UIImage *resultImage = nil;
CGFloat ar = self.size.width/self.size.height;
CGFloat wd = height*ar;
CGSize newSize = CGSizeMake(wd, height);
UIGraphicsBeginImageContext(newSize);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -newSize.height);
CGRect imageRect = CGRectMake(0, 0, newSize.width, newSize.height);
CGContextDrawImage(ctx, imageRect, self.CGImage);
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
//This method will take in the maxSizeLength and automatically
// detect the maximum side in image and reduce it to given
// maxSideLength maintaining the Aspect Ratio
-(UIImage*)getResizedMaxSideToLength:(CGFloat)maxSideLength
{
UIImage *src = [UIImage imageWithCGImage:self.CGImage];
if (src.size.width > maxSideLength)
{
src = [src getResizedToWidth:maxSideLength];
}
else
if (src.size.height >= maxSideLength )
{
src = [src getResizedToHeight:maxSideLength];
}
return src;
}
当您需要CGImage时,只需访问任何UIImage的CGImage属性即可获得,如下面的
CGImage *myCGImage = myUIImage.CGImage;