zoukankan      html  css  js  c++  java
  • 控制上传图片大小

     图片上传问题:上传到服务器的图片建议压缩一下,因为iphone拍出的照片比较大,如果直接上传无论是上传还是下载都比较慢而且费流量,体验不好.

    具体思路如下:

    先调整分辨率,分辨率可以自己设定一个值,大于的就缩小到这分辨率,小余的就保持原本分辨率。然后在根据最终大小来设置压缩比,比如传入maxSize = 100k,最终计算大概这个大小的压缩比。基本上最终出来的图片数据根据当前分辨率能保持差不多的大小同时不至于太模糊,跟微信,微博最终效果应该是差不多的,代码仍然有待优化!

    //控制图片大小

    - (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize

    {

        //先调整分辨率

        CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);

        

        CGFloat tempHeight = newSize.height / 1024;

        CGFloat tempWidth = newSize.width / 1024;

        

        if (tempWidth > 1.0 && tempWidth > tempHeight) {

            newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);

        }

        else if (tempHeight > 1.0 && tempWidth < tempHeight){

            newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);

        }

        

        UIGraphicsBeginImageContext(newSize);

        [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        

        //调整大小

        NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);

        NSUInteger sizeOrigin = [imageData length];

        NSUInteger sizeOriginKB = sizeOrigin / 1024;

        if (sizeOriginKB > maxSize) {

            NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.50);

            return finallImageData;

        }

        

        return imageData;

    }

  • 相关阅读:
    OC与JavaScript的交互
    号码运商判断
    iOS 适配https(AFNetworking3.0为例)
    UIlabel的字体自适应属性
    iOS10遇到有推送的Demo真机报错的解决
    UIView的setNeedsDisplay和setNeedsLayout
    ubuntu---设置路径时,profile和bashrc区别
    python---类的定义和使用
    ubuntu---鼠标变成空心十字架
    python--- 遍历一个图片文件夹 并 输出到txt文件
  • 原文地址:https://www.cnblogs.com/gaoxiaoniu/p/5566370.html
Copyright © 2011-2022 走看看