【问题标题】:Load .png into xcode and convert to UIImage将 .png 加载到 xcode 并转换为 UIImage
【发布时间】:2012-08-11 01:22:56
【问题描述】:

我对 Xcode、obj-c 等完全陌生,但我想使用 Parse.com 将图像保存到他们的服务器,他们说你必须使用这一行,将 UIImage 转换为 NSData

NSData *imageData = UIImagePNGRepresentation(image);

如何加载资源文件夹中的 .png 之一,然后将其转换为 UIImage?如果有帮助的话,我也在使用 Sparrow 框架。

编辑

我已经按照以下建议尝试了此代码。

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"terrainHexAtlas_v1@2x.png" ofType:@"png"];
UIImage *myImage = [UIImage imageWithContentsOfFile:imagePath];
NSData *imageData = UIImagePNGRepresentation(myImage);

PFFile *imageFile = [PFFile fileWithName:@"terrainHexAtlas_v1@2x.png" data:imageData];
    [imageFile save];

但似乎什么都没有发生。我在最后一行尝试了一个断点,vars imagePath、myImage、imageData 都是 00000000,我没有得到。

【问题讨论】:

    标签: xcode uiimage png sparrow-framework


    【解决方案1】:

    你应该遵循代码:

    //png
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"your_image" ofType:@"png"];
    UIImage *myImage = [UIImage imageWithContentsOfFile:imagePath];
    NSData *pngImageData = UIImagePNGRepresentation(myImage);
    
    //jpeg
    NSString *imagePath2 = [[NSBundle mainBundle] pathForResource:@"your_image" ofType:@"jpg"];
    UIImage *myImage2 = [UIImage imageWithContentsOfFile:imagePath2];
    NSData *jpegImageData = [UIImageJPEGRepresentation(myImage2, 1.0f)];
    

    在 pathForResource 中不包含扩展名。检查以下错误案例。

    // 不包含扩展名

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"your_image.png" ofType:nil];
    

    // 包含扩展名

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"your_image" ofType:@"png"];
    

    //有些人误判。错误代码。返回 nil

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"your_image.png" ofType:@"png"];
    

    【讨论】:

    • 我如何为 .jpg 做同样的事情?似乎没有 UIImageJPGRepresentation ?
    • 你应该按照以下方法使用:UIImageJPEGRepresentation(, );
    • 谢谢,我尝试了你的建议,但是当我在原始问题中更新时,什么都没有发生,没有任何东西被保存解析。
    • [[NSBundle mainBundle] pathForResource:@"terrainHexAtlas_v1@2x.png" ofType:@"png"];是错的。查看以下代码。 pathForResource 请检查。不要在 pathForResource 中包含扩展名。 [[NSBundle mainBundle] pathForResource:@"terrainHexAtlas_v1@2x" ofType:@"png"];
    猜你喜欢
    • 1970-01-01
    • 2015-04-05
    • 2013-11-29
    • 2015-11-24
    • 2021-09-03
    • 2016-09-04
    • 2019-10-27
    • 2013-05-10
    • 1970-01-01
    相关资源
    最近更新 更多