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

时间:2015-12-14 08:49:04

标签: ios swift uiimageview uiimagepickercontroller

我正在使用

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

但是我需要一个路径,但是如果没有路径,只能通过图像文件?

13 个答案:

答案 0 :(得分: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。这是设备或模拟器中使用的图像的实际大小。

class SampleSchema(Schema):
    class Meta:
        ordered = True

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

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

Swift 4及更早版

<body>
<div id="selection-panel" class="selection-panel" ng-controller="HelloWorldCtrl">
    <div>
        <uib-tabset type="pills" justified="true">
            <uib-tab ng-repeat="tab in tabs" heading="{{tab.title}}" select="update(tab.title)"></div>
            </uib-tab>
        </uib-tabset>
        <!-- This is moved outside -->
        <div id="data-panel" class="data-panel" ui-grid="gridOptions">
    </div>
</div>
<script src="js/app.js"></script>
</body>

Swift 5

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

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

答案 1 :(得分:8)

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

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

答案 2 :(得分:6)

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

答案 3 :(得分:2)

Swift 3

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

答案 4 :(得分: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)

答案 5 :(得分:1)

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

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

答案 6 :(得分:0)

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

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

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

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

答案 7 :(得分: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)

答案 8 :(得分: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
}

答案 9 :(得分: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")

答案 10 :(得分:0)

//快捷键4

    def guess_word(letr,empty,correct_word):
        if(letr.upper() in empty):
            return("Already guessed!!" + empty)
        elif(letr.upper() in correct_word):
            print("You gussing correctly")
            n=0
            for n in correct_word:
                print(type(empty))
                if correct_word[n]==letr:
                    print(type(empty))
                    empty.replace(empty[n],letr.upper())
                    n+=1
            return(empty)

答案 11 :(得分:0)

我致力于解决数据单位转换问题:

字节-> 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{"\($0)"}[unitLevel]

   return "\(String(format:"%.\(roundPoint)f",n)) \(ut)"
}

}

print(
convertStorageUnit(data:99922323343439789798789898989897987945454545920,
inputDataUnit:dataUnits.allCases.firstIndex(of: .B)!,roundPoint: 0)
)

输出: 8.87 PB

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

答案 12 :(得分:-1)

试试这个

import Darwin

...    

let size = malloc_size(&_attr)