如何在Swift中获取图像文件大小?

问题描述 投票:24回答:11

我在用

UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UIPopoverControllerDelegate

这些代表从我的画廊或我的相机中选择图像。那么,如何在选择图像后获得图像文件大小?

我想用这个:

let filePath = "your path here"
    var fileSize : UInt64 = 0

    do {
        let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)

        if let _attr = attr {
            fileSize = _attr.fileSize();
            print(fileSize)
        }
    } catch {
    }

但是在这里我需要一条路径,但是如果没有路径,我只能通过图像文件获得?

ios swift uiimageview uiimagepickercontroller
11个回答
61
投票

请检查谷歌1 kb到字节,它将是1000。

https://www.google.com/search?q=1+kb+%3D+how+many+bytes&oq=1+kb+%3D+how+many+bytes&aqs=chrome..69i57.8999j0j1&sourceid=chrome&ie=UTF-8


因此,在获得适当大小的同时,我通过在App Bundle和模拟器中的照片中添加图像来添加多个场景。我从Mac上拍摄的图像是299.0 KB。


场景1:将图像添加到应用程序包

在Xcode中添加图像时,图像的大小在项目目录中保持不变。但是你从它的路径得到它的大小将减少到257.0 KB。这是设备或模拟器中使用的图像的实际大小。

    guard let aStrUrl = Bundle.main.path(forResource: "1", ofType: "png") else { return }

   let aUrl = URL(fileURLWithPath: aStrUrl)
   print("Img size = \((Double(aUrl.fileSize) / 1000.00).rounded()) KB")

   extension URL {
        var attributes: [FileAttributeKey : Any]? {
            do {
                return try FileManager.default.attributesOfItem(atPath: path)
            } catch let error as NSError {
                print("FileAttribute error: \(error)")
            }
            return nil
        }

        var fileSize: UInt64 {
            return attributes?[.size] as? UInt64 ?? UInt64(0)
        }

        var fileSizeString: String {
            return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
        }

        var creationDate: Date? {
            return attributes?[.creationDate] as? Date
        }
    }

场景2:在模拟器中向照片添加图像

在模拟器或设备中向照片添加图像时,图像的大小从299.0 KB增加到393.0 KB。这是存储在设备或模拟器文档目录中的图像的实际大小。

斯威夫特4及更早

var image = info[UIImagePickerControllerOriginalImage] as! UIImage
var imgData: NSData = NSData(data: UIImageJPEGRepresentation((image), 1)) 
// var imgData: NSData = UIImagePNGRepresentation(image) 
// you can also replace UIImageJPEGRepresentation with UIImagePNGRepresentation.
var imageSize: Int = imgData.count
print("size of image in KB: %f ", Double(imageSize) / 1000.0)

斯威夫特5

let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage

let imgData = NSData(data: (info[UIImagePickerController.InfoKey.originalImage] as! UIImage).jpegData(compressionQuality: 1)!)
var imageSize: Int = imgData.count
print("actual size of image in KB: %f ", Double(imageSize) / 1000.0)   

通过添加.rounded()它将为您提供393.0 KB并且不使用它将提供393.442 KB。因此,请使用上述代码手动检查图像大小。由于图像的大小可能因不同的设备和mac而异。我只在Mac mini和模拟器iPhone XS上查看它。


0
投票

//斯威夫特4

if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        ///check image Size
       let imgData = NSData(data: UIImageJPEGRepresentation((pickedImage), 1)!)
       let imageSize: Int = imgData.count
       print("size of image in KB: %f ", Double(imageSize) / 1024.0)
       print("size of image in MB: %f ", Double(imageSize) / 1024.0 / 1024)    

    }

-1
投票

试试这个

import Darwin

...    

let size = malloc_size(&_attr)

6
投票

迅捷3/4:

if let imageData = UIImagePNGRepresentation(image) {
     let bytes = imageData.count
     let kB = Double(bytes) / 1000.0 // Note the difference
     let KB = Double(bytes) / 1024.0 // Note the difference
}

请注意kB和KB之间的差异。回答这里,因为在我的情况下,我们有一个问题,而我们认为千字节为1024字节,但服务器端认为它是1000字节,这引起了一个问题。 Link了解更多。

PS。几乎可以肯定你会使用kB(1000)。


2
投票

斯威夫特3

let uploadData = UIImagePNGRepresentation(image)
let array = [UInt8](uploadData)
print("Image size in bytes:\(array.count)")

1
投票
let selectedImage = info[UIImagePickerControllerOriginalImage] as!  UIImage 
let selectedImageData: NSData = NSData(data:UIImageJPEGRepresentation((selectedImage), 1)) 
let selectedImageSize:Int = selectedImageData.length 
print("Image Size: %f KB", selectedImageSize /1024.0)

1
投票
let data = UIImageJPEGRepresentation(image, 1)
let imageSize = data?.count

How to get the size of a UIImage in KB?重复


0
投票
let imageData = UIImageJPEGRepresentation(image, 1)
let imageSize = imageData?.count

UIImageJPEGRepresentation - 以JPEG格式返回指定图像的Data对象。值1.0表示压缩程度最小(接近原始图像)。

imageData?.count - 返回数据长度(字符数等于字节数)。

重要! UIImageJPEGRepresentation或UIImagePNGRepresentation不会返回原始图像。但是如果使用给定数据作为上传源 - 文件大小与服务器上的相同(甚至使用压缩)。


0
投票

Swift 4.2

let jpegData = image.jpegData(compressionQuality: 1.0)
let jpegSize: Int = jpegData?.count ?? 0
print("size of jpeg image in KB: %f ", Double(jpegSize) / 1024.0)

0
投票

细节

  • Xcode 10.2.1(10E1001),Swift 5

extension String {
    func getNumbers() -> [NSNumber] {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        let charset = CharacterSet.init(charactersIn: " ,.")
        return matches(for: "[+-]?([0-9]+([., ][0-9]*)*|[.][0-9]+)").compactMap { string in
            return formatter.number(from: string.trimmingCharacters(in: charset))
        }
    }

    // https://stackoverflow.com/a/54900097/4488252
    func matches(for regex: String) -> [String] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: [.caseInsensitive]) else { return [] }
        let matches  = regex.matches(in: self, options: [], range: NSMakeRange(0, self.count))
        return matches.compactMap { match in
            guard let range = Range(match.range, in: self) else { return nil }
            return String(self[range])
        }
    }
}

extension UIImage {
    func getFileSizeInfo(allowedUnits: ByteCountFormatter.Units = .useMB,
                         countStyle: ByteCountFormatter.CountStyle = .file) -> String? {
        // https://developer.apple.com/documentation/foundation/bytecountformatter
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = allowedUnits
        formatter.countStyle = countStyle
        return getSizeInfo(formatter: formatter)
    }

    func getFileSize(allowedUnits: ByteCountFormatter.Units = .useMB,
                     countStyle: ByteCountFormatter.CountStyle = .memory) -> Double? {
        guard let num = getFileSizeInfo(allowedUnits: allowedUnits, countStyle: countStyle)?.getNumbers().first else { return nil }
        return Double(truncating: num)
    }

    func getSizeInfo(formatter: ByteCountFormatter, compressionQuality: CGFloat = 1.0) -> String? {
        guard let imageData = jpegData(compressionQuality: compressionQuality) else { return nil }
        return formatter.string(fromByteCount: Int64(imageData.count))
    }
}

用法

guard let image = UIImage(named: "img") else { return }
if let imageSizeInfo = image.getFileSizeInfo() {
    print("\(imageSizeInfo), \(type(of: imageSizeInfo))") // 51.9 MB, String
}

if let imageSizeInfo = image.getFileSizeInfo(allowedUnits: .useBytes, countStyle: .file) {
    print("\(imageSizeInfo), \(type(of: imageSizeInfo))") // 54,411,697 bytes, String
}

if let imageSizeInfo = image.getFileSizeInfo(allowedUnits: .useKB, countStyle: .decimal) {
    print("\(imageSizeInfo), \(type(of: imageSizeInfo))") // 54,412 KB, String
}

if let size = image.getFileSize() {
    print("\(size), \(type(of: size))") // 51.9, Double
}

0
投票

试试这段代码(Swift 4.2)

extension URL {
    var attributes: [FileAttributeKey : Any]? {
        do {
            return try FileManager.default.attributesOfItem(atPath: path)
        } catch let error as NSError {
            print("FileAttribute error: \(error)")
        }
        return nil
    }

    var fileSize: UInt64 {
        return attributes?[.size] as? UInt64 ?? UInt64(0)
    }

    var fileSizeString: String {
        return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
    }

    var creationDate: Date? {
        return attributes?[.creationDate] as? Date
    }
}

并使用示例

guard let aStrUrl = Bundle.main.path(forResource: "example_image", ofType: "jpg") else { return }

        let aUrl = URL(fileURLWithPath: aStrUrl)

        print("Img size = \((Double(aUrl.fileSize) / 1000.00).rounded()) KB")
© www.soinside.com 2019 - 2024. All rights reserved.