1. 程式人生 > 實用技巧 >go語言中pdf轉圖片功能的實現(CentOS)

go語言中pdf轉圖片功能的實現(CentOS)

程式碼實現

步驟1:下載imagick

步驟2:go實現程式碼如下

package main

import (
	"os"
	"strconv"
	"gopkg.in/gographics/imagick.v2/imagick"
)

func main() {
	ConvertPdfToImage("test.pdf", 800, 1212, 200, 85)
}

//ConvertPdfToImage 轉換pdf為圖片格式
//@resolution:掃描精度
//@CompressionQuality:圖片質量: 1~100
func ConvertPdfToImage(bookname string, pageWidth uint, pageHeight uint, resolution float64, compressionQuality uint) (err error) {

	imagick.Initialize()
	defer imagick.Terminate()
	mw := imagick.NewMagickWand()
	//defer mw.Clear()
	defer mw.Destroy()

	if err := mw.SetResolution(resolution, resolution); err != nil {
		println("掃描精度設定失敗")
		return err
	}

	if err := mw.ReadImage(bookname); err != nil {
		println("檔案讀取失敗")
		return err
	}

	var pages = int(mw.GetNumberImages())
	println("頁數:", pages)

	//裁剪會使頁數增加
	addPages := 0
	path := ""
	for i := 0; i < pages; i++ {
		mw.SetIteratorIndex(i) // This being the page offset

		//壓平影象,去掉alpha通道,防止JPG中的alpha變黑,用在ReadImage之後
		if err := mw.SetImageAlphaChannel(imagick.ALPHA_CHANNEL_FLATTEN); err != nil {
			println("圖片")
			return err
		}

		mw.SetImageFormat("jpg")
		mw.SetImageCompression(imagick.COMPRESSION_JPEG)
		mw.SetImageCompressionQuality(compressionQuality)

		//如果width>height ,就裁剪成兩張
		pWidth := mw.GetImageWidth()
		pHeight := mw.GetImageHeight()

		//需要裁剪
		if pWidth > pHeight {

			//mw.ResizeImage(pageWidth*2, pageHeight, imagick.FILTER_UNDEFINED, 1.0)
			mw.ThumbnailImage(pageWidth*2, pageHeight)

			tempImage := mw.GetImageFromMagickWand()
			leftMw := imagick.NewMagickWandFromImage(tempImage) //由於返回的是指標,需要提前初始化,不然寫完左半業tempImage就變了

			//左半頁
			mw.CropImage(pageWidth, pageHeight, 0, 0)
			path = "./book/page" + strconv.Itoa(i+addPages) + ".jpg"
			mw.WriteImage(path)

			//右半頁
			leftMw.SetImageFormat("jpg")
			leftMw.SetImageCompression(imagick.COMPRESSION_JPEG)
			leftMw.SetImageCompressionQuality(compressionQuality)
			leftMw.CropImage(pageWidth, pageHeight, int(pageWidth), 0)
			addPages++
			path = "./book/page" + strconv.Itoa(i+addPages) + ".jpg"
			leftMw.WriteImage(path)
			leftMw.Destroy()

		} else {

			mw.ThumbnailImage(pageWidth, pageHeight)
			path = "./book/page" + strconv.Itoa(i+addPages) + ".jpg"
			mw.WriteImage(path)

		}

	}

	println("轉換完畢!")
	os.Exit(0) //模擬退出程式,刪掉!
	return nil
}

三、問題解決

在執行過程中報錯如下:

問題一:../gopkg.in/gographics/imagick.v2/imagick/drawing_wand.go:39: undefined: runtime.KeepAlive

解決:go版本過低導致

問題二:go build gopkg.in/gographics/imagick.v2/imagick: invalid flag in pkg-config --cflags: -fopenmp

解決:go版本原因。

問題三:/tmp/go-build695941684/command-line-arguments/_obj/exe/pdfconvert: error while loading shared libraries: libMagickWand-6.Q16.so.5: cannot open shared object file: No such file or directory

解決:進入目錄/user/local/lib中,執行ldconfig /user/local/lib。即解決。