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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34262791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:23:14  来源:igfitidea点击:

How to get image file size in Swift?

iosswiftuiimageviewuiimagepickercontroller

提问by Orkhan Alizade

I am using

我在用

UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UIPopoverControllerDelegate

these delegates for choosing image from my gallery or my camera. So, how can I get image file size after choosing an image?

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

I want to use this:

我想用这个:

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 {
    }

but here I need a path, but how can I get without a path, just by image file?

但在这里我需要一个路径,但是我怎么能没有路径,仅仅通过图像文件?

回答by Dhaivat Vyas

Please check the google for 1 kb to bytes it will be 1000.

请检查谷歌 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

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



So while getting the proper size I've added multiple scenario by adding image in App Bundle and in photos in simulator. Well the image which I took from my Mac was of 299.0 KB.

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



Scenario 1:Adding image to Application Bundle

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

On adding image in your Xcode the size of the image will remain same in project directory. But you get it from its path the size will be reduced to 257.0 KB. Which is the actual size of the image used in the device or simulator.

在您的 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
        }
    }

Scenario 2:Adding image to Photos in Simulator

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

On adding image to photos in simulator or device the size of the image increased from 299.0 KB to 393.0 KB. Which is the actual size of the image stored in the device or simulator's document directory.

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

Swift 4 and earlier

Swift 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)

Swift 5

斯威夫特 5

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

let imgData = NSData(data: image.jpegData(compressionQuality: 1)!)
var imageSize: Int = imgData.count
print("actual size of image in KB: %f ", Double(imageSize) / 1000.0)   

By adding .rounded() it will give you 393.0 KB and without using it it will give 393.442 KB. So please check the image size manually once using the above code. As the size of image may vary in different devices and mac. I've check it only on mac mini and simulator iPhone XS.

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

回答by Tung Fam

Swift 3/4:

斯威夫特 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
}

Please note the difference between kB and KB. Answering here because in my case we had an issue while we considered kilobyte as 1024 bytes but server side considered it as 1000 bytes which caused an issue. Linkto learn more.

请注意 kB 和 KB 之间的区别。在这里回答是因为在我的情况下,我们遇到了一个问题,而我们将千字节视为 1024 字节,但服务器端将其视为 1000 字节,这导致了问题。链接以了解更多信息。

PS. Almost sure you'll go with kB (1000).

附注。几乎可以肯定您会使用 kB (1000)。

回答by JP Aquino

Swift 3

斯威夫特 3

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

回答by Vasily Bodnarchuk

Details

细节

  • Xcode 10.2.1 (10E1001), Swift 5
  • Xcode 10.2.1 (10E1001),Swift 5

Solution

解决方案

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))
    }
}

Usage

用法

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
}

回答by Adarsh G J

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)

回答by efremidze

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

Duplicate of How to get the size of a UIImage in KB?

重复如何以 KB 为单位获取 UIImage 的大小?

回答by Govind Prajapati

Try this code (Swift 4.2)

试试这个代码(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
    }
}

And use example

并使用示例

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")

回答by Kundan

//Swift 4

//斯威夫特 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)    

    }

回答by Mir Karam

I make work around data units conversion :

我解决了数据单位转换:

Bytes -> KB -> MB -> GB -> ... -> Extremest Monster Data

字节 -> KB -> MB -> GB -> ... -> 极端怪物数据

enum dataUnits:CaseIterable {
case B      //Byte
case KB     //kilobyte
case MB     //megabyte
case GB     //gigabyte
case TB     //terabyte
case PB     //petabyte
case EB     //exabyte
case ZB     //zettabyte
case YB     //yottabyte
case BD     //Big Data
case BBx    // Extra Big Bytes
case BBxx   // 2 time Extra Big Bytes
case BBxxx  // 3 time Extra Big Bytes
case BBxxxx // 4 time Extra Big Bytes
case MBB    // Monster Big Bytes 
}
func convertStorageUnit(data n:Double,inputDataUnit unitLevel:Int,roundPoint:Int = 2,nG:Double = 1000.0)->String{
if(n>=nG){
    return convertStorageUnit(data:n/1024,inputDataUnit:unitLevel+1) 
}else{
    let ut = unitLevel > dataUnits.allCases.count + 1 ? "Extreme Monster Data" : dataUnits.allCases.map{"\(
print(
convertStorageUnit(data:99922323343439789798789898989897987945454545920,
inputDataUnit:dataUnits.allCases.firstIndex(of: .B)!,roundPoint: 0)
)
)"}[unitLevel] return "\(String(format:"%.\(roundPoint)f",n)) \(ut)" }

}

}

extension UIImage {

    public enum DataUnits: String {
        case byte, kilobyte, megabyte, gigabyte
    }

    func getSizeIn(_ type: DataUnits)-> String {

        guard let data = self.pngData() else {
            return ""
        }

        var size: Double = 0.0

        switch type {
        case .byte:
            size = Double(data.count)
        case .kilobyte:
            size = Double(data.count) / 1024
        case .megabyte:
            size = Double(data.count) / 1024 / 1024
        case .gigabyte:
            size = Double(data.count) / 1024 / 1024 / 1024
        }

        return String(format: "%.2f", size)
    }
}

output : 8.87 PB

输出:8.87 PB

Note: Input data length should be less than 64-bitOR Change data type According

注意:输入数据长度应小于 64 位更改数据类型根据

回答by Coder ACJHP

##代码##

Usage example : print("Image size \(yourImage.getSizeIn(.megabyte)) mb")

用法示例: print("Image size \(yourImage.getSizeIn(.megabyte)) mb")