1:引入系统的 ImageIO.framework
2:创建 UIImage 的 ImgSize 的类别
#import "UIImage+ImgSize.h"
#import <ImageIO/ImageIO.h>
@implementation UIImage (ImgSize)
/**
* 根据图片url获取网络图片尺寸
*/
+ (CGSize)getImageSizeWithURL:(id)URL{
NSURL* url =nil;
if([URLisKindOfClass:[NSURLclass]]) {
url = URL;
}
if([URLisKindOfClass:[NSStringclass]]) {
url = [NSURLURLWithString:URL];
}
if(!URL) {
returnCGSizeZero;
}
CGImageSourceRefimageSourceRef =CGImageSourceCreateWithURL((CFURLRef)url,NULL);
CGFloatwidth =0, height =0;
if(imageSourceRef) {
//获取图像属性
CFDictionaryRefimageProperties =CGImageSourceCopyPropertiesAtIndex(imageSourceRef,0,NULL);
//以下是对手机32位、64位的处理
if(imageProperties !=NULL) {
CFNumberRefwidthNumberRef =CFDictionaryGetValue(imageProperties,kCGImagePropertyPixelWidth);
#if defined(__LP64__) && __LP64__
if(widthNumberRef !=NULL) {
CFNumberGetValue(widthNumberRef,kCFNumberFloat64Type, &width);
}
CFNumberRefheightNumberRef =CFDictionaryGetValue(imageProperties,kCGImagePropertyPixelHeight);
if(heightNumberRef !=NULL) {
CFNumberGetValue(heightNumberRef,kCFNumberFloat64Type, &height);
}
#else
if(widthNumberRef !=NULL) {
CFNumberGetValue(widthNumberRef, kCFNumberFloat32Type, &width);
}
CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
if(heightNumberRef !=NULL) {
CFNumberGetValue(heightNumberRef, kCFNumberFloat32Type, &height);
}
#endif
/*****************此处解决返回图片宽高相反问题*****************/
// 图像旋转的方向属性
NSIntegerorientation = [(__bridgeNSNumber*)CFDictionaryGetValue(imageProperties,kCGImagePropertyOrientation)integerValue];
CGFloattemp =0;
switch(orientation) { // 如果图像的方向不是正的,则宽高互换
case UIImageOrientationLeft: // 向左逆时针旋转90度
case UIImageOrientationRight: // 向右顺时针旋转90度
case UIImageOrientationLeftMirrored: // 在水平翻转之后向左逆时针旋转90度
case UIImageOrientationRightMirrored: { // 在水平翻转之后向右顺时针旋转90度
temp = width;
width = height;
height = temp;
}
break;
default:
break;
}
/*****************此处解决返回图片宽高相反问题*****************/
CFRelease(imageProperties);
}
CFRelease(imageSourceRef);
}
returnCGSizeMake(width, height);
}
@end
3:使用
导入头文件:#import "UIImage+ImgSize.h"
//图片内容
UIImageView * img = [UIImageView new];
img.contentMode = UIViewContentModeScaleAspectFill;
img.clipsToBounds = YES;
CGSizesize = [UIImage getImageSizeWithURL:[NSString stringWithFormat:@"%@%@",ImageNationURL,UnPackStr(dic[@"value"])]];
NSLog(@"宽:%f, 高:%f", size.width,size.height);
img.widthHeight=XY(SCREEN_WIDTH, (SCREEN_WIDTH)*size.height/size.width);
img.leftTop=XY(0, 0);
[img sd_setImageWithUrlStr:UnPackStr(dic[@"value"]) placeholderImage:IMAGE_HEAD_DEFAULT withWidth:0 withHeight:0];
网友评论