将UIImage转换为NSData并在Swift中转换回UIImage?

时间:2015-08-30 14:40:25

标签: ios swift uiimage png nsdata

我正在尝试将UIImage保存到NSData,然后将NSData读回Swift中的新UIImage。要将UIImage转换为NSData我正在使用以下代码:

let imageData: NSData = UIImagePNGRepresentation(myImage)

如何将imageData(即NSData)转换回新的UIImage

10 个答案:

答案 0 :(得分:110)

#include <iostream> #include <vector> #include <string> #include <sstream> using namespace std; int main(){ string a = " test 1234 test 5678"; stringstream strstr(a); string test; vector<int>numvec; int num; while(strstr>>num || !strstr.eof()){ if(strstr.fail()){ strstr.clear(); string kpz; strstr>>kpz; } numvec.push_back(num); } for(int i = 0;numvec.size();++i){ cout<<numvec[i]<<'\t'; } } 假设图像的比例为1。

答案 1 :(得分:56)

感谢。帮助了我很多。转换为Swift 3并工作

保存:let data = UIImagePNGRepresentation(image)

加载:let image = UIImage(data: data)

答案 2 :(得分:30)

使用imageWithData:方法,将其转换为Swift UIImage(data:)

let image : UIImage = UIImage(data: imageData)

答案 3 :(得分:13)

现在在 Swift 4.2 中,您可以使用pngData() UIImage的新实例方法从图片中获取数据

let profileImage = UIImage(named:"profile")!
let imageData = profileImage.pngData()

答案 4 :(得分:7)

保存为数据:

从StoryBoard,如果您想在MainStoryBoard的imageView上保存“图像”数据,以下代码将起作用。

let image = UIImagePNGRepresentation(imageView.image!) as NSData?

将“image”加载到imageView: 看感叹号“!”,“?”密切关注这是否与此相同。

imageView.image = UIImage(data: image as! Data)

“NSData”类型在此过程中自动转换为“数据”类型。

答案 5 :(得分:5)

为了安全执行代码,请使用if-let阻止Data阻止应用崩溃&amp; ,因为函数UIImagePNGRepresentation返回一个可选值。

if let img = UIImage(named: "TestImage.png") {
    if let data:Data = UIImagePNGRepresentation(img) {
       // Handle operations with data here...         
    }
}
  

注意:数据是Swift 3+类。使用数据而不是NSData   Swift 3 +

通用图像操作(如png&amp; jpg):

if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
        if let data:Data = UIImagePNGRepresentation(img) {
               handleOperationWithData(data: data)     
        } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
               handleOperationWithData(data: data)     
        }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

使用扩展名:

extension UIImage {

    var pngRepresentationData: Data? {
        return UIImagePNGRepresentation(self)
    }

    var jpegRepresentationData: Data? {
        return UIImageJPEGRepresentation(self, 1.0)
    }
}

*******
if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
      if let data = img.pngRepresentationData {
              handleOperationWithData(data: data)     
      } else if let data = img.jpegRepresentationData {
              handleOperationWithData(data: data)     
     }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

答案 6 :(得分:4)

图像到数据:-

    if let img = UIImage(named: "xxx.png") {
        let pngdata = img.pngData()
    }

   if let img = UIImage(named: "xxx.jpeg") {
        let jpegdata = img.jpegData(compressionQuality: 1)
    }

数据到图像:-

 let image = UIImage(data: pngData)

答案 7 :(得分:0)

详细信息

  • Xcode 10.2.1(10E1001),Swift 5

解决方案1 ​​

guard let image = UIImage(named: "img") else { return }
let jpegData = image.jpegData(compressionQuality: 1.0)
let pngData = image.pngData()

解决方案2.1

extension UIImage {
    func toData (options: NSDictionary, type: CFString) -> Data? {
        guard let cgImage = cgImage else { return nil }
        return autoreleasepool { () -> Data? in
            let data = NSMutableData()
            guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, type, 1, nil) else { return nil }
            CGImageDestinationAddImage(imageDestination, cgImage, options)
            CGImageDestinationFinalize(imageDestination)
            return data as Data
        }
    }
}

解决方案2.1的使用

// about properties: https://developer.apple.com/documentation/imageio/1464962-cgimagedestinationaddimage
let options: NSDictionary =     [
    kCGImagePropertyOrientation: 6,
    kCGImagePropertyHasAlpha: true,
    kCGImageDestinationLossyCompressionQuality: 0.5
]

// https://developer.apple.com/documentation/mobilecoreservices/uttype/uti_image_content_types
guard let data = image.toData(options: options, type: kUTTypeJPEG) else { return }
let size = CGFloat(data.count)/1000.0/1024.0
print("\(size) mb")

解决方案2.2

extension UIImage {

    func toJpegData (compressionQuality: CGFloat, hasAlpha: Bool = true, orientation: Int = 6) -> Data? {
        guard cgImage != nil else { return nil }
        let options: NSDictionary =     [
                                            kCGImagePropertyOrientation: orientation,
                                            kCGImagePropertyHasAlpha: hasAlpha,
                                            kCGImageDestinationLossyCompressionQuality: compressionQuality
                                        ]
        return toData(options: options, type: .jpeg)
    }

    func toData (options: NSDictionary, type: ImageType) -> Data? {
        guard cgImage != nil else { return nil }
        return toData(options: options, type: type.value)
    }
    // about properties: https://developer.apple.com/documentation/imageio/1464962-cgimagedestinationaddimage
    func toData (options: NSDictionary, type: CFString) -> Data? {
        guard let cgImage = cgImage else { return nil }
        return autoreleasepool { () -> Data? in
            let data = NSMutableData()
            guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, type, 1, nil) else { return nil }
            CGImageDestinationAddImage(imageDestination, cgImage, options)
            CGImageDestinationFinalize(imageDestination)
            return data as Data
        }
    }

    // https://developer.apple.com/documentation/mobilecoreservices/uttype/uti_image_content_types
    enum ImageType {
        case image // abstract image data
        case jpeg                       // JPEG image
        case jpeg2000                   // JPEG-2000 image
        case tiff                       // TIFF image
        case pict                       // Quickdraw PICT format
        case gif                        // GIF image
        case png                        // PNG image
        case quickTimeImage             // QuickTime image format (OSType 'qtif')
        case appleICNS                  // Apple icon data
        case bmp                        // Windows bitmap
        case ico                        // Windows icon data
        case rawImage                   // base type for raw image data (.raw)
        case scalableVectorGraphics     // SVG image
        case livePhoto                  // Live Photo

        var value: CFString {
            switch self {
            case .image: return kUTTypeImage
            case .jpeg: return kUTTypeJPEG
            case .jpeg2000: return kUTTypeJPEG2000
            case .tiff: return kUTTypeTIFF
            case .pict: return kUTTypePICT
            case .gif: return kUTTypeGIF
            case .png: return kUTTypePNG
            case .quickTimeImage: return kUTTypeQuickTimeImage
            case .appleICNS: return kUTTypeAppleICNS
            case .bmp: return kUTTypeBMP
            case .ico: return kUTTypeICO
            case .rawImage: return kUTTypeRawImage
            case .scalableVectorGraphics: return kUTTypeScalableVectorGraphics
            case .livePhoto: return kUTTypeLivePhoto
            }
        }
    }
}

解决方案2.2的使用

let compressionQuality: CGFloat = 0.4
guard let data = image.toJpegData(compressionQuality: compressionQuality) else { return }
printSize(of: data)

let options: NSDictionary =     [
                                    kCGImagePropertyHasAlpha: true,
                                    kCGImageDestinationLossyCompressionQuality: compressionQuality
                                ]
guard let data2 = image.toData(options: options, type: .png) else { return }
printSize(of: data2)

  

问题

图像表示将占用大量cpu和内存资源。因此,在这种情况下,最好遵循几个规则:

-不要在主队列上运行jpegData(compressionQuality:)

-只能同时运行一个jpegData(compressionQuality:)

错误:

for i in 0...50 {
    DispatchQueue.global(qos: .utility).async {
        let quality = 0.02 * CGFloat(i)
        //let data = image.toJpegData(compressionQuality: quality)
        let data = image.jpegData(compressionQuality: quality)
        let size = CGFloat(data!.count)/1000.0/1024.0
        print("\(i), quality: \(quality), \(size.rounded()) mb")
    }
}

右:

let serialQueue = DispatchQueue(label: "queue", qos: .utility, attributes: [], autoreleaseFrequency: .workItem, target: nil)

for i in 0...50 {
    serialQueue.async {
        let quality = 0.02 * CGFloat(i)
        //let data = image.toJpegData(compressionQuality: quality)
        let data = image.jpegData(compressionQuality: quality)
        let size = CGFloat(data!.count)/1000.0/1024.0
        print("\(i), quality: \(quality), \(size.rounded()) mb")
    }
}

链接

答案 8 :(得分:0)

雨燕5

让您创建为UIImage的图像成为图像

image.pngData() as NSData? 

答案 9 :(得分:0)

使用它作为一个简单的解决方案

static var UserProfilePhoto = UIImage()
guard let image = UIImage(named: "Photo") else { return }
guard let pngdata = image.pngData() else { return }
UserProfilePhoto = UIImage(data: pngdata)!