Jan*_*Jan 3 xcode objective-c uiimage nsdata ios
有没有办法从 UIImage 获取以 KB 为单位的文件大小,而不从 didFinishPickingMediaWithInfo 获取该图像?所呈现的图像来自相册。
我尝试了以下代码,但这给出了以下结果:图像大小(KB):0.000000
- (void)setImage:(UIImage *)image
{
_image = image;
self.imageView.image = image;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupView];
self.backgroundColor = [UIColor whiteColor];
panGestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(beingDragged:)];
[self addGestureRecognizer:panGestureRecognizer];
// prepare image view
self.imageView = [[UIImageView alloc]initWithFrame:self.bounds];
self.imageView.clipsToBounds = YES;
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
[self addSubview:self.imageView];
NSData *imgData = [[NSData alloc] initWithData:UIImageJPEGRepresentation((_image), 0.5)];
int imageSize = imgData.length;
NSLog(@"size of image in KB: %f ", imageSize/1024.0);
overlayView = [[OverlayView alloc]initWithFrame:CGRectMake(self.frame.size.width/2-100, 0, 100, 100)];
overlayView.alpha = 0;
[self addSubview:overlayView];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
以下是计算主目录或文档中文件大小的示例:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"yourimagename.png"]
Run Code Online (Sandbox Code Playgroud)
文件sie计算:
filesize = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil] fileSize];
NSLog(@"%lld",filesize);
Run Code Online (Sandbox Code Playgroud)
在添加文件大小之前,您可以将其添加到 .m 文件中
@interface ViewController () {
long long filesize;
}
Run Code Online (Sandbox Code Playgroud)
这将产生字节,如果您尝试将这些字节转换为 kb,您可以使用 NSByteCountFormatter,它会为您处理所有数学运算:
NSByteCountFormatter *sizeFormatter = [[NSByteCountFormatter alloc] init];
sizeFormatter.countStyle = NSByteCountFormatterCountStyleFile;
Run Code Online (Sandbox Code Playgroud)
然后这样称呼它:
[sizeFormatter stringFromByteCount:filesize]
Run Code Online (Sandbox Code Playgroud)
如果图像没有保存在磁盘上,您可以这样计算大小:
NSData *imgData = UIImageJPEGRepresentation(_image, 1);
filesize = [imgData length]; //filesize in this case will be an int not long long so use %d to NSLog it
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5223 次 |
| 最近记录: |