首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UIImagePNGRepresentation是否返回空数据?

UIImagePNGRepresentation是否返回空数据?
EN

Stack Overflow用户
提问于 2013-07-03 14:00:44
回答 3查看 4.5K关注 0票数 7

我正在尝试制作缩略图并保存到文档目录。但问题是,当我试图将缩略图转换为NSData时。它返回nil。

这是我的代码,

代码语言:javascript
复制
  UIImage *thumbNailimage=[image thumbnailImage:40 transparentBorder:0.2 cornerRadius:0.2 interpolationQuality:1.0];
NSData *thumbNailimageData = UIImagePNGRepresentation(thumbNailimage);// Returns nil
[thumbNailimageData writeToFile:[DOCUMENTPATH stringByAppendingPathComponent:@"1.png"] atomically:NO];

那么,问题是什么呢?我也尝试过UIImageJPEGRepresentation,但它对我不起作用。

谢谢。

EN

回答 3

Stack Overflow用户

发布于 2014-09-18 13:57:31

试试这个:

代码语言:javascript
复制
UIGraphicsBeginImageContext(originalImage.size);
[originalImage drawInRect:CGRectMake(0, 0, originalImage.size.width, originalImage.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

这将创建原始UIImage的副本。然后,您可以调用UIImagePNGRepresentation,它将正常工作。

票数 17
EN

Stack Overflow用户

发布于 2013-07-03 15:27:57

试试这段代码,

代码语言:javascript
复制
-(void) createThumbnail
{
   UIImage *originalImage = imgView2.image; // Give your original Image
   CGSize destinationSize = CGSizeMake(25, 25); // Give your Desired thumbnail Size
   UIGraphicsBeginImageContext(destinationSize);
   [originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
   UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
   NSData *thumbNailimageData = UIImagePNGRepresentation(newImage);
   UIGraphicsEndImageContext();
   [thumbNailimageData writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"1.png"] atomically:NO];
}

希望这对你有帮助,祝你编码愉快

票数 4
EN

Stack Overflow用户

发布于 2016-12-28 17:26:08

对于Swift程序员来说,Rickster的回答帮了我很大的忙!UIImageJPEGRepresentation在选择某个图片时会使我的应用崩溃。我正在分享我的UIImage扩展(或者Objective-C术语中的Category )。

代码语言:javascript
复制
import UIKit

extension UIImage {

    /**
     Creates the UIImageJPEGRepresentation out of an UIImage
     @return Data
     */

    func generateJPEGRepresentation() -> Data {

        let newImage = self.copyOriginalImage()
        let newData = UIImageJPEGRepresentation(newImage, 0.75)

        return newData!
    }

    /**
     Copies Original Image which fixes the crash for extracting Data from UIImage
     @return UIImage
     */

    private func copyOriginalImage() -> UIImage {
        UIGraphicsBeginImageContext(self.size);
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();

        return newImage!
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17440741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档