为什么在命令行应用程序中在 Retina Mac 上绘制 NSImage 会使图像像素加倍

问题描述

我正在 Retina Mac 上的 macOS 上的命令行应用程序中将一些图像缩放到特定大小。一切正常,我得到了我要求的尺寸。如果我画进去(在这种情况下是水印),像素数会加倍。如果我跳过绘制水印的块,则生成的图像大小正确。

// add watermark - result is NSImage
if let localResult = result
{
    result = NSImage(size: localResult.size,flipped: true,drawingHandler: { (bound) -> Bool in

        localResult.draw(in: NSRect(x: 0,y: 0,width: localResult.size.width,height: localResult.size.height),from: NSRect.zero,operation: .copy,fraction: 1.0,respectFlipped: true,hints: nil)
        let imageSize = localResult.size
        let copySize = copyrightImage.size

        let desiredWidth = imageSize.width/4
        let a = desiredWidth
        let d = a * copySize.height / copySize.width

        let r = NSRect(x: imageSize.width/2-desiredWidth/2,y: imageSize.height-d-10,width: desiredWidth,height: d)

        copyrightImage.draw(in: r,operation: .exclusion,fraction: 0.8,hints: nil)

        return true
    })
}

if let result = result,let outputImage = result.cgImage(forProposedRect: nil,context: nil,hints: nil)
{
    if let imageRep = NSBitmapImageRep(cgImage: outputImage).converting(to: .sRGB,renderingIntent: .perceptual)
    {
        if let finalData = imageRep.representation(using: .jpeg,properties: [NSBitmapImageRep.PropertyKey.compressionFactor : compression])
        {
            return SizedResult(data: finalData,pixelsWide: result.representations[0].pixelsWide,pixelsHigh: result.representations[0].pixelsHigh)
        }
    }

如何让 macOS 不使像素数翻倍,或以其他方式或使用其他 API 解决此问题?这些图像是用于网络应用程序的,需要是我指定的大小,它们不会被绘制到 Mac 的屏幕上。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)