使用JMagick給圖片加文字浮水印的中文問題全解決java程式

來源:互聯網
上載者:User

ImageMagick (TM) 是一個免費的建立、編輯、合成圖片的軟體。它可以讀取、轉換、寫入多種格式的圖片。圖片切割、顏色替換、各種效果的應用,圖片的旋轉、組合,文本,直線, 多邊形,橢圓,曲線,附加到圖片伸展旋轉。ImageMagick是免費軟體:全部源碼開放,可以自由使用,複製,修改,發布。它遵守GPL許可協議。它 可以運行於大多數的作業系統。ImageMagick的大多數功能的使用都來源於命令列工具。

ImageMagick API的Java版實現JMagick也是一個非常好用的圖片處理工具。在Windows和Linux平台下均可以使用。

在使用JMagick 的過程中,一般會遇到以下中文問題:無法使用中文給圖片加文字浮水印。

在Linux下解決此 JMagick給圖片加文字浮水印的中文問題的Java程式例如下。

/**
*
* @param filePath
* @param text
* @param opacity 透明度 0 - 100, 0 為不透明
* @return
*/
public static String addTextToPicture(String filePath, String text,
int opacity) {

System.setProperty(”jmagick.systemclassloader”, “no”);
int idx = filePath.indexOf(’.');
String newFileName = filePath.substring(0, idx) + “_twm” + filePath.substring(idx);

try {
ImageInfo info = new ImageInfo(filePath);

if (filePath.toUpperCase().endsWith(”JPG”) || filePath.toUpperCase().endsWith(”JPEG”)) {
info.setCompression(CompressionType.JPEGCompression); //壓縮類別為JPEG格式
info.setPreviewType(PreviewType.JPEGPreview); //預覽格式為JPEG格式
info.setQuality(95);
}

MagickImage aImage = new MagickImage(info);

DrawInfo aInfo = new DrawInfo(info);

aInfo.setFill(PixelPacket.queryColorDatabase(”green”));
aInfo.setUnderColor(PixelPacket.queryColorDatabase(”yellow”));
aInfo.setOpacity(0);
aInfo.setPointsize(20);

//aInfo.setFont(”Arial”);  // 英文使用此字型也可

//注意這裡解決中文字型問題,有以下兩行才可正常顯示
String fontPath = "/home/user1/wmfont/simsun.ttf";
    aInfo.setFont(fontPath);
aInfo.setTextAntialias(true);

//Step 3: Writing The Text
aInfo.setText(text);
aInfo.setGeometry(”+40+60″);
/*
if(width > height){
aInfo.setGeometry(”+” +(480-140)+”+”+(int)((480/p)-10)); // 加文字浮水印在圖象上的位置
}
else{
aInfo.setGeometry(”+”+(int)((480*p)-140)+”+” +(480-10)); //加文字浮水印在圖象上的位置
}
*/

//Step 4: Annotating
aImage.annotateImage(aInfo);

//Step 5: Writing the new file
aImage.setFileName(newFileName);
aImage.writeImage(info);
aImage.destroyImages();

aImage = null;

} catch (MagickException e) {

}

return newFileName;
}

使用此程式,可以使用java程式在圖片中加入網站地址,或者自己的簽名等著作權資訊了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.