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

时间:2021-11-22 16:22:42

I am trying to convert the raw image data to jpeg in swift. But unfortunately, the jpeg image created is skewed. Please find below the code used for the conversion.

我试图将原始图像数据转换为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])

Here's the converted jpeg image

这是转换后的jpeg图像

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

Any help or pointers would be greatly appreciated. Thanks in advance!

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

1 个解决方案

#1


0  

Try this, change imageName to what you want, and save it in any Directory

试试这个,将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")
        }
    }

#1


0  

Try this, change imageName to what you want, and save it in any Directory

试试这个,将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")
        }
    }