简体   繁体   English

将 UIImage 转换为字节

[英]Convert UIImage into bytes

I am getting UIImage using UIImagePickerController.我正在使用 UIImagePickerController 获取 UIImage。 How can i calculate number of bytes hold by that Image in kb/mb?我如何计算该图像以 kb/mb 为单位保存的字节数?

Using that values I have to make logic that user cant add Images more than size of 1MB使用该值,我必须制定用户不能添加超过 1MB 大小的图像的逻辑

Sure you can.你当然可以。 Convert the UIImage to a NSData object, which has the length property, which will give you its size in bytes.UIImage转换为NSData object,它具有length属性,它将为您提供以字节为单位的大小。 Then you can easily calculate the size in whatever unit you need.然后,您可以轻松计算所需的任何单位的大小。

So for example:例如:

    UIImage *img = [UIImage imageNamed:@"some.png"];
    NSData *dataObj = UIImageJPEGRepresentation(img, 1.0);
    int bytes = [dataObj length];
    //convert into whatever unit you need

You can get image size from following delegate method of UIImagePickerController您可以从 UIImagePickerController 的以下委托方法获取图像大小

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
     if([UIImageJPEGRepresentation(image, 1.0) length]> MAX_SIZE)
     {
         //Code here
     }
}

Here, You can see, I have converted Image into data, and [data length] can give bytes length.在这里,您可以看到,我已经将Image转换为数据,并且[数据长度]可以给出字节长度。

Rather than stopping the user from uploading images of more than 1MB, you would serve your user better by scaling and compressing the image to save space I suspect.与其阻止用户上传超过 1MB 的图像,不如通过缩放和压缩图像来更好地为用户服务,以节省我怀疑的空间。 However to answer your question, one way would simply be;但是,要回答您的问题,一种方法就是;

-(void)imagePickerController:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *) info {


NSData *imageData = UIImagePNGRepresentation(image); // Or UIImageJPEGRepresentation 
long sizeInBytes = [imageData length];

// do stuff

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM