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