zoukankan      html  css  js  c++  java
  • SDWebImage 加载一些大的图片的时候导致程序崩溃

    在  UIImage+MultiFormat这个类里面添加如下压缩方法,

    +(UIImage *)compressImageWith:(UIImage *)image

    {

        float imageWidth = image.size.width;

        float imageHeight = image.size.height;

        float width = 640;

        float height = image.size.height/(image.size.width/width);

        

        float widthScale = imageWidth /width;

        float heightScale = imageHeight /height;

        

        // 创建一个bitmap的context

        // 并把它设置成为当前正在使用的context

        UIGraphicsBeginImageContext(CGSizeMake(width, height));

        

        if (widthScale > heightScale) {

            [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];

        }

        else {

            [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];

        }

        

        // 从当前context中创建一个改变大小后的图片

        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

        // 使当前的context出堆栈

        UIGraphicsEndImageContext();

        

        return newImage;

        

    }

    再在上面箭头代码后面对图片进行压缩

    1. + (UIImage *)sd_imageWithData:(NSData *)data {

          UIImage *image;

          NSString *imageContentType = [NSData sd_contentTypeForImageData:data];

          if ([imageContentType isEqualToString:@"image/gif"]) {

              image = [UIImage sd_animatedGIFWithData:data];

          }

      #ifdef SD_WEBP

          else if ([imageContentType isEqualToString:@"image/webp"])

          {

              image = [UIImage sd_imageWithWebPData:data];

          }

      #endif

          else {

              image = [[UIImage alloc] initWithData:data];

              

              if (data.length/1024 > 128) {

                  image = [self compressImageWith:image];

              }

              UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];

              if (orientation != UIImageOrientationUp) {

                  image = [UIImage imageWithCGImage:image.CGImage

                                              scale:image.scale

                                        orientation:orientation];

              }

          }

          return image;

      }

    到了这里还需要进行最后一步。就是在SDWebImageDownloaderOperation的connectionDidFinishLoading方法里面的:

    UIImage *image = [UIImage sd_imageWithData:self.imageData];

    //将等比压缩过的image在赋在转成data赋给self.imageData
    NSData *data = UIImageJPEGRepresentation(image, 1);
    self.imageData = [NSMutableData dataWithData:data];

       再配合    [[SDImageCache sharedImageCachesetValue:nil forKey:@"memCache"];(图片加载后使用)大功告成,亲测内存基本变化不大,自动释放也来得及。

  • 相关阅读:
    【转】Android版本升级同时Sqlite数据库的升级及之前数据的保留
    MC 在1分钟图拿出5分钟,15分钟,30分钟,1小时的K线
    MC 自己平均
    MT4 做指标模版
    MQL5 获取最后一单 利润
    MT5基础知识
    DDE复盘流程
    安装lnmp(linux nginx mysql php)
    centos 7 切换运行模式
    安装 flash player
  • 原文地址:https://www.cnblogs.com/danMing-love/p/6873110.html
Copyright © 2011-2022 走看看