聊天界面向后台发送图片时,发现选择相册图片会出现图片翻转的现象,调用相机拍照上传时,照片由于过大,导致界面交互缓慢,以下为解决方案
图片翻转解决方法
if (image.imageOrientation != UIImageOrientationUp)
{
UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
[image drawInRect:(CGRect){0,0,image.size}];
UIImage *normalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
image = normalImage;
}
图片发送缓慢解决方法
NSString *imageName = [NSString stringWithFormat:@"%lf.jpg", [NSDate date].timeIntervalSince1970];
NSString *imagePath = [NSFileManager pathUserChatImage:imageName];
NSData *saveData = (UIImageJPEGRepresentation(image, 1.0));
[[NSFileManager defaultManager] createFileAtPath:imagePath contents:saveData attributes:nil];
//UIImagePNGRepresentation(image) ? UIImagePNGRepresentation(image) :
NSData *imageData = [ZYSmartChatImageType reSizeImageData:image maxImageSize:320 maxSizeWithKB:1024];
在此处调用+ (NSData *)reSizeImageData:(UIImage *)sourceImage maxImageSize:(CGFloat)maxImageSize maxSizeWithKB:(CGFloat) maxSize方法,具体方法内容如下
+ (NSData *)reSizeImageData:(UIImage *)sourceImage maxImageSize:(CGFloat)maxImageSize maxSizeWithKB:(CGFloat) maxSize
{
if (maxSize <= 0.0) maxSize = 1024.0;
if (maxImageSize <= 0.0) maxImageSize = 1024.0;
//先调整分辨率
CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
CGFloat tempHeight = newSize.height / maxImageSize;
CGFloat tempWidth = newSize.width / maxImageSize;
if (tempWidth > 1.0 && tempWidth > tempHeight) {
newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
}
else if (tempHeight > 1.0 && tempWidth < tempHeight){
newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
}
UIGraphicsBeginImageContext(newSize);
[sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//调整大小
NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
CGFloat sizeOriginKB = imageData.length / 1024.0;
CGFloat resizeRate = 0.9;
while (sizeOriginKB > maxSize && resizeRate > 0.1) {
imageData = UIImageJPEGRepresentation(newImage,resizeRate);
sizeOriginKB = imageData.length / 1024.0;
resizeRate -= 0.1;
}
return imageData;
}
此模块中遇到的其它问题:
iOS聊天界面后台数据发送过快,导致展示cell的frame没有重新计算