2017-04-13 1 views
0

Im 현재 swift를 사용하여 이미지의 크기를 조정하려고합니다. 이 shouldnt은 30 분 동안 C#으로 스케일링 솔루션을 구현 했으므로 까다로운 작업이됩니다. 그러나 2 일 동안 멈추었습니다.이미지 크기 조정 OSX Swift

스택 글을 통해 검색 중이거나 크롤링을 시도했지만 아무 소용이 없습니다. 사람들이 사용 내가 본 두 가지 주요 솔루션은 다음과 같습니다

A function written in Swift to resize an NSImage proportionately

resizeNSImage.swift

An Obj C Implementation of the above link

그래서 내가 가장 효율적인/최소 CPU 집약적 인 솔루션을 사용하는 것을 선호, 내 연구에 따르면 옵션 2입니다. 옵션 2로 인해 NSImage.lockfocus()NSImage.unlockFocus을 사용하면 이미지가 비 망막 Mac에서 잘 확대됩니다. 그러나 망막 맥의 크기를 두 배로 늘린다. 나는 이것이 망막 맥의 픽셀 밀도로 인한 것으로 알고 있어야합니다,하지만 나는 HiDPI 사양을 무시하고 그냥 정상적인 규모의 작업을 수행하는 스케일링 솔루션이 필요합니다.

이것은 옵션 1에 대한 더 많은 연구를하게 만들었습니다. 사운드 기능처럼 보이지만 입력 된 이미지의 크기를 그대로 유지 한 다음 반환 된 이미지를 저장할 때 파일 크기를 두 배로 만듭니다 (아마도 픽셀 밀도로 인해). 나는 정확한 스택 (found here)을 사용하여 다른 스택 포스트를 발견했다. 두 가지 제안 된 답변 중 첫 번째는 작동하지 않으며 두 번째는 내가 사용하려고 시도한 다른 구현입니다.

사람들이 스위프트- 답변을 게시 할 수 있다면 Obj C와 반대로, 나는 그것을 매우 고맙게 생각합니다!

편집 : - :

func getSizeProportions(oWidth: CGFloat, oHeight: CGFloat) -> NSSize { 

    var ratio:Float = 0.0 
    let imageWidth = Float(oWidth) 
    let imageHeight = Float(oHeight) 

    var maxWidth = Float(0) 
    var maxHeight = Float(600) 

    if (maxWidth == 0) { 
     maxWidth = imageWidth 
    } 

    if(maxHeight == 0) { 
     maxHeight = imageHeight 
    } 

    // Get ratio (landscape or portrait) 
    if (imageWidth > imageHeight) { 
     // Landscape 
     ratio = maxWidth/imageWidth; 
    } 
    else { 
     // Portrait 
     ratio = maxHeight/imageHeight; 
    } 

    // Calculate new size based on the ratio 
    let newWidth = imageWidth * ratio 
    let newHeight = imageHeight * ratio 

    return NSMakeSize(CGFloat(newWidth), CGFloat(newHeight)) 
} 


func resizeImage(image:NSImage) -> NSImage { 
    print("original: ", image.size.width, image.size.height) 

    // Cast the NSImage to a CGImage 
    var imageRect:CGRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) 
    let imageRef = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil) 

    // Create a new NSSize object with the newly calculated size 
    let newSize = NSSize(width: CGFloat(450), height: CGFloat(600)) 
    //let newSize = getSizeProportions(oWidth: CGFloat(image.size.width), oHeight: CGFloat(image.size.height)) 

    // Create NSImage from the CGImage using the new size 
    let imageWithNewSize = NSImage(cgImage: imageRef!, size: newSize) 

    print("scaled: ", imageWithNewSize.size.width, imageWithNewSize.size.height) 

    return NSImage(data: imageWithNewSize.tiffRepresentation!)! 
} 

편집 2 :

바와 같이 Zneak 지적 여기에 최초의 솔루션 내 구현의 복사본입니다 나는이 개 기능으로 나누어 한 : 반환 된 이미지를 디스크에 저장해야합니다. 두 구현을 모두 사용하여 내 저장 함수는 파일을 디스크에 성공적으로 씁니다. 난 내 저장 기능은 내 현재 크기 조정 구현을 속이고 있다고 생각 해달라고하지만, 난 그냥 경우 어쨌든 그것을 첨부했습니다 :

func saveAction(image: NSImage, url: URL) { 

    if let tiffdata = image.tiffRepresentation, 
    let bitmaprep = NSBitmapImageRep(data: tiffdata) { 

    let props = [NSImageCompressionFactor: Appearance.imageCompressionFactor] 
    if let bitmapData = NSBitmapImageRep.representationOfImageReps(in: [bitmaprep], using: .JPEG, properties: props) { 

     let path: NSString = "~/Desktop/out.jpg" 
     let resolvedPath = path.expandingTildeInPath 

     try! bitmapData.write(to: URL(fileURLWithPath: resolvedPath), options: []) 

     print("Your image has been saved to \(resolvedPath)") 
    } 
} 
+0

"해야할까요"또는 "해서는 안됩니다"? 사소한 것은 쉬운 것을 의미합니다. 또한 화면에 표시하거나 디스크 또는 다른 것으로 다시 쓰는 목적으로이 작업을 수행하고 있습니까? 더 크게 또는 더 작은 크기로 확장? – zneak

+0

OP 편집 : – amartin94

+0

그리고 메신저 디스크에 다시 쓰려고 스케일링 – amartin94

답변

0

다른 사람이이 문제가 발생에 - 난을 찾으려고 많은 시간을 보내고 결국 방법은이 작업을 수행하고, 단지 (일반 맥, 망막 2 1) 화면의 배율 계수를 받고 결국에 ... 코드는 다음과 같습니다

func getScaleFactor() -> CGFloat { 
    return NSScreen.main()!.backingScaleFactor 
} 

을 그럼 당신은 스케일 인자를 일단 정상적으로 조절하거나 망막의 크기를 반으로 줄이십시오 :

if (scaleFactor == 2) { 
    //halve size proportions for saving on Retina Macs 
    return NSMakeSize(CGFloat(oWidth*ratio)/2, CGFloat(oHeight*ratio)/2) 
} else { 
    return NSMakeSize(CGFloat(oWidth*ratio), CGFloat(oHeight*ratio)) 
} 
+0

특정 배율 인수를 확인하는 대신, CGFloat (너비 * 비율)/scaleFactor'. 이렇게하면 Apple은 backing scale factor가 다른 값인 장치/모드를 도입하면 코드가 올바르게 작동합니다. 그러나 * 먼저 0을 확인하십시오! – DarkDust