簡體   English   中英

快速將原始圖像數據轉換為jpeg

[英]Convert raw image data to jpeg in 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圖像

轉換后的圖像

任何幫助或指針將不勝感激。 提前致謝!

嘗試此操作,將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")
        }
    }

終於找到答案了

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM