代码之家  ›  专栏  ›  技术社区  ›  Aravind G S

在swift中将原始图像数据转换为jpeg

  •  1
  • Aravind G S  · 技术社区  · 6 年前

    我正在尝试在swift中将原始图像数据转换为jpeg。但不幸的是,创建的jpeg图像是倾斜的。请在下面找到用于转换的代码。

    let rawPtr = (rawImgData as NSData).bytes
    let mutableRawPtr = UnsafeMutableRawPointer.init(mutating: rawPtr)
    let context = CGContext.init(data: mutableRawPtr,
                                 width: 750,
                                 height: 1334,
                                 bitsPerComponent: 32,
                                 bytesPerRow: (8 * 750)/8,
                                 space: CGColorSpaceCreateDeviceRGB(),
                                 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue())
    let imageRef = CGContext.makeImage(context!)
    let imageRep = NSBitmapImageRep(cgImage: imageRef()!)
    let finalData = imageRep.representation(using: .jpeg,
                                            properties: [NSBitmapImageRep.PropertyKey.compressionFactor : 0.5])
    

    这是转换后的jpeg图像

    Converted Image

    任何帮助或指点都将不胜感激。提前感谢!

    2 回复  |  直到 6 年前
        1
  •  1
  •   Aravind G S    5 年前

    终于找到了答案

    var width:size_t?
    var height:size_t?
    let bitsPerComponent:size_t = 8
    var bytesPerRow:size_t?
    var bitmapInfo: UInt32
    if #available(OSX 10.12, *) {
        bitmapInfo = UInt32(CGImageAlphaInfo.premultipliedFirst.rawValue) | UInt32(CGImageByteOrderInfo.order32Little.rawValue)
    } else {
        bitmapInfo = UInt32(CGImageAlphaInfo.premultipliedFirst.rawValue)
    }
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    
    do {
        let streamAttributesFuture = self.bitmapStream?.streamAttributes()
        streamAttributesFuture?.onQueue(.main, notifyOfCompletion: { (streamAttributesFut) in
    
        })
        try streamAttributesFuture?.await()
        let dict = streamAttributesFuture?.result
        width = (dict?.attributes["width"] as! Int)
        height = (dict?.attributes["height"] as! Int)
        bytesPerRow = (dict?.attributes["row_size"] as! Int)
    
    } catch let frameError{
        print("frame error = \(frameError)")
        return
    }
    
    let rawPtr = (data as NSData).bytes
    let mutableRawPtr = UnsafeMutableRawPointer.init(mutating: rawPtr)
    let context = CGContext.init(data: mutableRawPtr, width: width!, height: height!, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow!, space: colorSpace, bitmapInfo: bitmapInfo)
    if context == nil {
        return
    }
    
    let imageRef = context?.makeImage()
    
    let scaledWidth = Int(Double(width!) / 1.5)
    let scaledHeight = Int(Double(height!) / 1.5)
    
    let resizeCtx = CGContext.init(data: nil, width: scaledWidth, height: scaledHeight, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow!, space: colorSpace, bitmapInfo: bitmapInfo)
    resizeCtx?.draw(imageRef!, in: CGRect(x: 0, y: 0, width: scaledWidth, height: scaledHeight))
    
    resizeCtx?.interpolationQuality = .low
    
    let resizedImgRef = resizeCtx?.makeImage()
    let imageRep = NSBitmapImageRep(cgImage: resizedImgRef!)
    
    let finalData = imageRep.representation(using: .jpeg, properties: [NSBitmapImageRep.PropertyKey.compressionFactor : compression])
    
        2
  •  0
  •   A.Munzer    6 年前

    尝试此操作,将imageName更改为所需的名称,并将其保存在任何目录中

    func convertToJPEG(image: UIImage) {
            if let jpegImage = UIImageJPEGRepresentation(image, 1.0){
                do {
                    //Convert
                    let tempDirectoryURL = URL(fileURLWithPath:  NSTemporaryDirectory(), isDirectory: true)
                    let newFileName = "\(imageName.append(".JPG"))"
                    let targetURL = tempDirectoryURL.appendingPathComponent(newFileName)
                    try jpegImage.write(to: targetURL, options: [])
                }catch {
                    print (error.localizedDescription)
                    print("FAILED")
                }
            }else{
                print("FAILED")
            }
        }