You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cocoa:Swift开发macOS应用时截屏保存如何缩放图像到指定尺寸

失效原因

kCGImagePropertyPixelWidth、kCGImagePropertyPixelHeight属于图像元数据字段,仅用于记录图像尺寸信息,不会触发实际的像素重采样操作,因此修改这两个参数无法实现图像缩放效果。

正确实现方案

你需要先对捕获得到的原始CGImage进行手动缩放重绘,再将缩放后的图像写入目标文件,具体实现代码如下:

import CoreGraphics
import ImageIO
import UniformTypeIdentifiers

// 1. 捕获原始屏幕图像
guard let originalImg = CGDisplayCreateImage(CGMainDisplayID()) else {
    print("Unable to capture screen!")
    return
}

// 2. 定义目标缩放尺寸
let targetSize = CGSize(width: 900, height: 380)
// 适配Retina屏幕,若不需要可直接使用targetSize作为渲染尺寸
let scale = NSScreen.main?.backingScaleFactor ?? 1.0
let renderSize = CGSize(width: targetSize.width * scale, height: targetSize.height * scale)

// 3. 重绘生成缩放后的图像
guard let context = CGContext(
    data: nil,
    width: Int(renderSize.width),
    height: Int(renderSize.height),
    bitsPerComponent: originalImg.bitsPerComponent,
    bytesPerRow: 0,
    space: originalImg.colorSpace ?? CGColorSpaceCreateDeviceRGB(),
    bitmapInfo: originalImg.bitmapInfo.rawValue
) else {
    print("Unable to create graphics context!")
    return
}
// 开启高质量插值优化缩放画质
context.interpolationQuality = .high
context.draw(originalImg, in: CGRect(origin: .zero, size: renderSize))
guard let scaledImg = context.makeImage() else {
    print("Unable to generate scaled image!")
    return
}

// 4. 保存缩放后的图像到本地
guard let destination = FileManager.default.urls(
    for: .downloadsDirectory,
    in: .userDomainMask
).first?.appendingPathComponent("shot.jpg", isDirectory: false) else {
    print("Unable to get save path!")
    return
}

let saveProperties: CFDictionary = [
    kCGImageDestinationLossyCompressionQuality: 0.9 // 可调整压缩质量,范围0~1,数值越大画质越高
] as CFDictionary

guard let dest = CGImageDestinationCreateWithURL(
    destination as CFURL,
    UTType.jpeg.identifier as CFString,
    1,
    nil
) else {
    print("Unable to create image destination!")
    return
}

CGImageDestinationAddImage(dest, scaledImg, saveProperties)
if !CGImageDestinationFinalize(dest) {
    print("Failed to save image!")
}

兼容旧版macOS说明:若你的项目需要适配较低版本的系统,可将UTType.jpeg.identifier替换为kUTTypeJPEG,同时导入CoreServices框架即可。

  • 若不需要适配Retina屏幕的物理像素密度,直接将renderSize替换为targetSize即可
  • 可根据自己的需求调整kCGImageDestinationLossyCompressionQuality的参数值,平衡JPG文件的画质和体积

内容的提问来源于stack exchange,提问作者Vin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:15:05