0
我無法在python中創建有效的CGBitmapContext。它只是返回null值,然後導致其他所有內容抱怨缺少定義和python崩潰。我嘗試將內存分配設置爲None,這意味着它應該自行排除,但這也不起作用。我不認爲objC緩衝區也被分配。任何幫助將不勝感激。我的CGBitmapContext出了什麼問題?
#!/usr/bin/python
import os, sys, objc
from Quartz import *
os.environ["CG_CONTEXT_SHOW_BACKTRACE"] = '1'
resolution = 300 #dpi
scale = resolution/72
cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB)
# Options might be: kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedLast \ or FIRST
transparency = kCGImageAlphaNoneSkipLast
#Save image to file
def writeImage (image, url, type, options):
destination = CGImageDestinationCreateWithURL(url, type, 1, None)
CGImageDestinationAddImage(destination, image, options)
CGImageDestinationFinalize(destination)
CFRelease(destination)
return
if __name__ == '__main__':
for filename in sys.argv[1:]:
pdf = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename(filename))
numPages = CGPDFDocumentGetNumberOfPages(pdf)
shortName = os.path.splitext(filename)[0]
# For each page, create a file
for i in range (1, numPages+1):
page = CGPDFDocumentGetPage(pdf, i)
if page:
#Get mediabox
mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox)
x = CGRectGetWidth(mediaBox)
y = CGRectGetHeight(mediaBox)
x *= scale
y *= scale
# Allocate Memory, in this day and age.
try:
rasterData = objc.allocateBuffer(int(4 * x * y))
except MemoryError: break
# Create a Bitmap Context
ctx = CGBitmapContextCreate(rasterData, x, y, 8, x, cs, transparency)
CGContextSaveGState (ctx)
CGContextScaleCTM(ctx, scale,scale)
CGContextDrawPDFPage(ctx, page)
CGContextRestoreGState(ctx)
# Convert to an "Image"
image = CGBitmapContextCreateImage(ctx)
# Create unique filename per page
outFile = shortName + str(i) + ".tiff"
url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, outFile, len(outFile), False)
# kUTTypeJPEG, kUTTypeTIFF, kUTTypePNG
type = 'kUTTypeTIFF'
options = {
kCGImagePropertyTIFFXResolution : 300,
kCGImagePropertyTIFFYResolution : 300
}
writeImage (image, url, type, options)
CGContextRelease(ctx)
del page
「CGBitmapContextCreate」的'bytesPerRow'參數看起來不對。如果您的位圖的像素寬度爲x像素,並且它是每個組件8位的RGBA上下文,則每個像素需要4個字節,因此bytesPerRow應該是「x * 4」。 (請注意,當你分配內存時,你的數學運算是正確的。) –
是的,我只是讓0讓Mac爲自己工作,而腳本似乎在其他地方失敗了。所以,進展。 – benwiggy