从 CGImageRef 创建的 UIImage 失败并显示 UIImagePNGRepresentation
我使用以下代码从较大的 UIImage 中裁剪并创建一个新的 UIImage。我已将问题与函数 CGImageCreateWithImageInRect() 隔离开来,该函数似乎没有按照我想要的方式设置某些 CGImage 属性。 :-) 问题是调用函数 UIImagePNGRepresentation() 失败,返回 nil。
CGImageRef origRef = [stillView.image CGImage];
CGImageRef cgCrop = CGImageCreateWithImageInRect( origRef, theRect);
UIImage *imgCrop = [UIImage imageWithCGImage:cgCrop];
...
NSData *data = UIImagePNGRepresentation ( imgCrop);
-- libpng 错误:没有将 IDAT 写入文件
知道从 UIImage 中裁剪出矩形可能会出现什么问题或替代方案吗?
I'm using the following code to crop and create a new UIImage out of a bigger one. I've isolated the issue to be with the function CGImageCreateWithImageInRect() which seem to not set some CGImage property the way I want. :-) The problem is that a call to function UIImagePNGRepresentation() fails returning a nil.
CGImageRef origRef = [stillView.image CGImage];
CGImageRef cgCrop = CGImageCreateWithImageInRect( origRef, theRect);
UIImage *imgCrop = [UIImage imageWithCGImage:cgCrop];
...
NSData *data = UIImagePNGRepresentation ( imgCrop);
-- libpng error: No IDATs written into file
Any idea what might wrong or alternative for cropping a rect out of UIImage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我遇到了同样的问题,但只是在 iOS 3.2 上测试兼容性时。在 4.2 上它工作正常。
最后我发现了这个 http:// www.hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/ 两者都适用,尽管有点冗长!
我将其转换为 UIImage 上的类别:
UIImage+Crop.h
UIImage+Crop.m
I had the same problem, but only when testing compatibility on iOS 3.2. On 4.2 it works fine.
In the end I found this http://www.hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/ which works on both, albeit a little more verbose!
I converted this into a category on UIImage:
UIImage+Crop.h
UIImage+Crop.m
在 PNG 中存在各种块,一些包含调色板信息,一些实际图像数据和一些其他信息,这是一个非常有趣的标准。 IDAT块是实际包含图像数据的位。如果没有“IDAT 写入文件”,则 libpng 从输入数据创建 PNG 时遇到一些问题。
我不知道你的 stillView.image 到底是什么,但是当你向你的代码传递一个肯定有效的 CGImageRef 时会发生什么? theRect 中的实际值是多少?如果你的 theRect 超出了图像的边界,那么你试图用来制作 UIImage 的 cgCrop 很容易为零 - 或不为零,但不包含图像或宽度和高度为 0 的图像,使 libpng 无法工作和。
In a PNG there are various chunks present, some containing palette info, some actual image data and some other information, it's a very interesting standard. The IDAT chunk is the bit that actually contains the image data. If there's no "IDAT written into file" then libpng has had some issue creating a PNG from the input data.
I don't know exactly what your stillView.image is, but what happens when you pass your code a CGImageRef that is certainly valid? What are the actual values in theRect? If your theRect is beyond the bounds of the image then the cgCrop you're trying to use to make the UIImage could easily be nil - or not nil, but containing no image or an image with width and height 0, giving libpng nothing to work with.
看来您正在尝试的解决方案应该有效,但我建议使用这个:
It seems the solution you are trying should work, but I recommend to use this: