use of java.awt.image.BufferedImage in project jmonkeyengine by jMonkeyEngine.
the class LwjglDisplay method imagesToByteBuffers.
private ByteBuffer[] imagesToByteBuffers(Object[] images) {
ByteBuffer[] out = new ByteBuffer[images.length];
for (int i = 0; i < images.length; i++) {
BufferedImage image = (BufferedImage) images[i];
out[i] = imageToByteBuffer(image);
}
return out;
}
use of java.awt.image.BufferedImage in project AozoraEpub3 by hmdev.
the class AozoraEpub3Applet method convertFile.
/** 内部用変換関数 Appletの設定を引数に渡す
* @param srcFile 変換するファイル txt,zip,cbz,(rar,cbr)
* @param dstPath 出力先パス
* @param txtIdx Zip内テキストファイルの位置
*/
private void convertFile(File srcFile, File dstPath, String ext, int txtIdx, boolean imageOnly) {
//パラメータ設定
if (!"txt".equals(ext) && !"txtz".equals(ext) && !"zip".equals(ext) && !"cbz".equals(ext) && !"rar".equals(ext)) {
if (!"png".equals(ext) && !"jpg".equals(ext) && !"jpeg".equals(ext) && !"gif".equals(ext)) {
LogAppender.println("txt, txtz, zip, cbz rar 以外は変換できません");
}
return;
}
//表紙にする挿絵の位置-1なら挿絵は使わない
int coverImageIndex = -1;
//表紙情報追加
String coverFileName = this.jComboCover.getEditor().getItem().toString();
if (coverFileName.equals(this.jComboCover.getItemAt(0).toString())) {
//先頭の挿絵
coverFileName = "";
coverImageIndex = 0;
} else if (coverFileName.equals(this.jComboCover.getItemAt(1).toString())) {
//入力ファイルと同じ名前+.jpg/.png
coverFileName = AozoraEpub3.getSameCoverFileName(srcFile);
} else if (coverFileName.equals(this.jComboCover.getItemAt(2).toString())) {
//表紙無し
coverFileName = null;
}
boolean isFile = "txt".equals(ext);
ImageInfoReader imageInfoReader = new ImageInfoReader(isFile, srcFile);
//zip内の画像をロード
try {
if (!isFile) {
if ("rar".equals(ext)) {
//Rar内の画像情報読み込み 画像のみならファイル順も格納
imageInfoReader.loadRarImageInfos(srcFile, imageOnly);
} else {
//Zip内の画像情報読み込み 画像のみならファイル順も格納
imageInfoReader.loadZipImageInfos(srcFile, imageOnly);
}
}
} catch (Exception e) {
e.printStackTrace();
LogAppender.error(e.getMessage());
}
//BookInfo取得
BookInfo bookInfo = null;
try {
if (!imageOnly) {
//テキストファイルからメタ情報や画像単独ページ情報を取得
bookInfo = AozoraEpub3.getBookInfo(srcFile, ext, txtIdx, imageInfoReader, this.aozoraConverter, this.jComboEncType.getSelectedItem().toString(), BookInfo.TitleType.indexOf(this.jComboTitle.getSelectedIndex()), jCheckPubFirst.isSelected());
}
} catch (Exception e) {
LogAppender.error("ファイルが読み込めませんでした : " + srcFile.getPath());
return;
}
if (this.convertCanceled) {
LogAppender.println("変換処理を中止しました : " + srcFile.getAbsolutePath());
return;
}
Epub3Writer writer = this.epub3Writer;
try {
if (!isFile) {
//Zip内の画像情報をbookInfoに設定
if (imageOnly) {
LogAppender.println("画像のみのePubファイルを生成します");
//画像出力用のBookInfo生成
bookInfo = new BookInfo(srcFile);
bookInfo.imageOnly = true;
//Writerを画像出力用派生クラスに入れ替え
writer = this.epub3ImageWriter;
if (imageInfoReader.countImageFileInfos() == 0) {
LogAppender.error("画像がありませんでした");
return;
}
//名前順で並び替え
imageInfoReader.sortImageFileNames();
//先頭画像をbookInfoに設定しておく
//if (coverImageIndex == 0) {
// bookInfo.coverImage = imageInfoReader.getImage(0);
//}
//画像数をプログレスバーに設定 xhtml出力で+1 画像出力で+10
this.jProgressBar.setMaximum(imageInfoReader.countImageFileInfos() * 11);
jProgressBar.setValue(0);
jProgressBar.setStringPainted(true);
} else {
//画像がなければプレビュー表示しないようにindexを-1に
if (imageInfoReader.countImageFileNames() == 0)
coverImageIndex = -1;
//zipテキストならzip内の注記以外の画像も追加
imageInfoReader.addNoNameImageFileName();
}
}
} catch (Exception e) {
e.printStackTrace();
LogAppender.error(e.getMessage());
}
if (bookInfo == null) {
LogAppender.error("書籍の情報が取得できませんでした");
return;
}
//テキストなら行数/100と画像数をプログレスバーに設定
if (bookInfo.totalLineNum > 0) {
if (isFile)
this.jProgressBar.setMaximum(bookInfo.totalLineNum / 10 + imageInfoReader.countImageFileNames() * 10);
else
this.jProgressBar.setMaximum(bookInfo.totalLineNum / 10 + imageInfoReader.countImageFileInfos() * 10);
jProgressBar.setValue(0);
jProgressBar.setStringPainted(true);
}
//表紙目次ページ出力設定
bookInfo.insertCoverPage = this.jCheckCoverPage.isSelected();
bookInfo.insertTocPage = this.jCheckTocPage.isSelected();
bookInfo.insertCoverPageToc = this.jCheckCoverPageToc.isSelected();
bookInfo.insertTitleToc = this.jCheckTitleToc.isSelected();
//表題の見出しが非表示で行が追加されていたら削除
if (!bookInfo.insertTitleToc && bookInfo.titleLine >= 0) {
bookInfo.removeChapterLineInfo(bookInfo.titleLine);
}
//目次縦書き
bookInfo.setTocVertical(this.jRadioTocV.isSelected());
//縦書き横書き設定追加
bookInfo.vertical = this.jRadioVertical.isSelected();
this.aozoraConverter.vertical = bookInfo.vertical;
//表題左右中央
if (!this.jCheckTitlePage.isSelected()) {
bookInfo.titlePageType = BookInfo.TITLE_NONE;
} else if (this.jRadioTitleNormal.isSelected()) {
bookInfo.titlePageType = BookInfo.TITLE_NORMAL;
} else if (this.jRadioTitleMiddle.isSelected()) {
bookInfo.titlePageType = BookInfo.TITLE_MIDDLE;
} else if (this.jRadioTitleHorizontal.isSelected()) {
bookInfo.titlePageType = BookInfo.TITLE_HORIZONTAL;
}
//先頭からの場合で指定行数以降なら表紙無し
if ("".equals(coverFileName) && !imageOnly) {
try {
int maxCoverLine = Integer.parseInt(this.jTextMaxCoverLine.getText());
if (maxCoverLine > 0 && (bookInfo.firstImageLineNum == -1 || bookInfo.firstImageLineNum >= maxCoverLine)) {
coverImageIndex = -1;
coverFileName = null;
} else {
coverImageIndex = bookInfo.firstImageIdx;
}
} catch (Exception e) {
}
}
//表紙ページの情報をbookInfoに設定
bookInfo.coverFileName = coverFileName;
bookInfo.coverImageIndex = coverImageIndex;
String[] titleCreator = BookInfo.getFileTitleCreator(srcFile.getName());
if (jCheckUseFileName.isSelected()) {
//ファイル名優先ならテキスト側の情報は不要
bookInfo.title = "";
bookInfo.creator = "";
if (titleCreator[0] != null)
bookInfo.title = titleCreator[0];
if (titleCreator[1] != null)
bookInfo.creator = titleCreator[1];
} else {
//テキストから取得できなければファイル名を利用
if (bookInfo.title == null || bookInfo.title.length() == 0) {
bookInfo.title = titleCreator[0] == null ? "" : titleCreator[0];
if (bookInfo.creator == null || bookInfo.creator.length() == 0)
bookInfo.creator = titleCreator[1] == null ? "" : titleCreator[1];
}
}
if (this.convertCanceled) {
LogAppender.println("変換処理を中止しました : " + srcFile.getAbsolutePath());
return;
}
//前回の変換設定を反映
BookInfoHistory history = this.getBookInfoHistory(bookInfo);
if (history != null) {
if (bookInfo.title.length() == 0)
bookInfo.title = history.title;
bookInfo.titleAs = history.titleAs;
if (bookInfo.creator.length() == 0)
bookInfo.creator = history.creator;
bookInfo.creatorAs = history.creatorAs;
if (bookInfo.publisher == null)
bookInfo.publisher = history.publisher;
//表紙設定
if (jCheckCoverHistory.isSelected()) {
bookInfo.coverEditInfo = history.coverEditInfo;
bookInfo.coverFileName = history.coverFileName;
bookInfo.coverExt = history.coverExt;
bookInfo.coverImageIndex = history.coverImageIndex;
//確認ダイアログ表示しない場合はイメージを生成
if (!this.jCheckConfirm.isSelected() && bookInfo.coverEditInfo != null) {
try {
this.jConfirmDialog.jCoverImagePanel.setBookInfo(bookInfo);
if (bookInfo.coverImageIndex >= 0 && bookInfo.coverImageIndex < imageInfoReader.countImageFileNames()) {
bookInfo.coverImage = imageInfoReader.getImage(bookInfo.coverImageIndex);
} else if (bookInfo.coverImage == null && bookInfo.coverFileName != null) {
bookInfo.loadCoverImage(bookInfo.coverFileName);
}
bookInfo.coverImage = this.jConfirmDialog.jCoverImagePanel.getModifiedImage(this.coverW, this.coverH);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
String outExt = this.jComboExt.getEditor().getItem().toString().trim();
////////////////////////////////
//Kindleチェック
File kindlegen = null;
writer.setIsKindle(false);
if (outExt.startsWith(".mobi")) {
kindlegen = new File(this.jarPath + "kindlegen.exe");
if (!kindlegen.isFile()) {
kindlegen = new File(this.jarPath + "kindlegen");
if (!kindlegen.isFile()) {
kindlegen = null;
}
}
if (kindlegen == null) {
JOptionPane.showMessageDialog(this, "kindlegenがありません\nkindlegen.exeをjarファイルの場所にコピーしてください", "kindlegenエラー", JOptionPane.WARNING_MESSAGE);
LogAppender.println("変換処理をキャンセルしました");
return;
}
writer.setIsKindle(true);
}
//確認ダイアログ 変換ボタン押下時にbookInfo更新
if (this.jCheckConfirm.isSelected()) {
//表題と著者設定 ファイル名から設定
String title = "";
String creator = "";
if (bookInfo.title != null)
title = bookInfo.title;
if (bookInfo.creator != null)
creator = bookInfo.creator;
this.jConfirmDialog.setChapterCheck(jCheckChapterSection.isSelected(), jCheckChapterH.isSelected(), jCheckChapterH1.isSelected(), jCheckChapterH2.isSelected(), jCheckChapterH3.isSelected(), jCheckChapterName.isSelected(), jCheckChapterNumOnly.isSelected() || jCheckChapterNumTitle.isSelected() || jCheckChapterNumParen.isSelected() || jCheckChapterNumParenTitle.isSelected(), jCheckChapterPattern.isSelected());
this.jConfirmDialog.showDialog(srcFile, (dstPath != null ? dstPath.getAbsolutePath() : srcFile.getParentFile().getAbsolutePath()) + File.separator, title, creator, this.jComboTitle.getSelectedIndex(), jCheckPubFirst.isSelected(), bookInfo, imageInfoReader, this.jFrameParent.getLocation(), coverW, coverH);
//ダイアログが閉じた後に再開
if (this.jConfirmDialog.canceled) {
this.convertCanceled = true;
LogAppender.println("変換処理を中止しました : " + srcFile.getAbsolutePath());
return;
}
if (this.jConfirmDialog.skipped) {
this.setBookInfoHistory(bookInfo);
LogAppender.println("変換をスキップしました : " + srcFile.getAbsolutePath());
return;
}
//変換前確認のチェックを反映
if (!this.jConfirmDialog.jCheckConfirm2.isSelected())
jCheckConfirm.setSelected(false);
//確認ダイアログの値をBookInfoに設定
bookInfo.title = this.jConfirmDialog.getMetaTitle();
bookInfo.creator = this.jConfirmDialog.getMetaCreator();
bookInfo.titleAs = this.jConfirmDialog.getMetaTitleAs();
bookInfo.creatorAs = this.jConfirmDialog.getMetaCreatorAs();
bookInfo.publisher = this.jConfirmDialog.getMetaPublisher();
//著者が空欄なら著者行もクリア
if (bookInfo.creator.length() == 0)
bookInfo.creatorLine = -1;
//プレビューでトリミングされていたらbookInfo.coverImageにBufferedImageを設定 それ以外はnullにする
BufferedImage coverImage = this.jConfirmDialog.jCoverImagePanel.getModifiedImage(this.coverW, this.coverH);
if (coverImage != null) {
//Epub3Writerでイメージを出力
bookInfo.coverImage = coverImage;
//元の表紙は残す
if (this.jConfirmDialog.jCheckReplaceCover.isSelected())
bookInfo.coverImageIndex = -1;
} else {
bookInfo.coverImage = null;
}
this.setBookInfoHistory(bookInfo);
} else {
//表題の見出しが非表示で行が追加されていたら削除
if (!bookInfo.insertTitleToc && bookInfo.titleLine >= 0) {
bookInfo.removeChapterLineInfo(bookInfo.titleLine);
}
}
boolean autoFileName = this.jCheckAutoFileName.isSelected();
boolean overWrite = this.jCheckOverWrite.isSelected();
//出力ファイル
File outFile = null;
//Kindleは一旦tmpファイルに出力
File outFileOrg = null;
if (kindlegen != null) {
outFile = AozoraEpub3.getOutFile(srcFile, dstPath, bookInfo, autoFileName, ".epub");
File mobiFile = new File(outFile.getAbsolutePath().substring(0, outFile.getAbsolutePath().length() - 4) + "mobi");
if (!overWrite && (mobiFile.exists() || (outExt.endsWith(".epub") && outFile.exists()))) {
LogAppender.println("変換中止: " + srcFile.getAbsolutePath());
if (mobiFile.exists())
LogAppender.println("ファイルが存在します: " + mobiFile.getAbsolutePath());
else
LogAppender.println("ファイルが存在します: " + outFile.getAbsolutePath());
return;
}
outFileOrg = outFile;
try {
outFile = File.createTempFile("kindle", ".epub", outFile.getParentFile());
if (!outExt.endsWith(".epub"))
outFile.deleteOnExit();
} catch (IOException e) {
outFile = outFileOrg;
outFileOrg = null;
}
} else {
outFile = AozoraEpub3.getOutFile(srcFile, dstPath, bookInfo, autoFileName, outExt);
//上書き確認
if (!overWrite && outFile.exists()) {
LogAppender.println("変換中止: " + srcFile.getAbsolutePath());
LogAppender.println("ファイルが存在します: " + outFile.getAbsolutePath());
return;
}
}
/*
if (overWrite && outFile.exists()) {
int ret = JOptionPane.showConfirmDialog(this, "ファイルが存在します\n上書きしますか?\n(取り消しで変換キャンセル)", "上書き確認", JOptionPane.YES_NO_CANCEL_OPTION);
if (ret == JOptionPane.NO_OPTION) {
LogAppender.println("変換中止: "+srcFile.getAbsolutePath());
return;
} else if (ret == JOptionPane.CANCEL_OPTION) {
LogAppender.println("変換中止: "+srcFile.getAbsolutePath());
convertCanceled = true;
LogAppender.println("変換処理をキャンセルしました");
return;
}
}*/
////////////////////////////////
//変換実行
AozoraEpub3.convertFile(srcFile, ext, outFile, this.aozoraConverter, writer, this.jComboEncType.getSelectedItem().toString(), bookInfo, imageInfoReader, txtIdx);
imageInfoReader = null;
//画像は除去
bookInfo.coverImage = null;
//変換中にキャンセルされた場合
if (this.convertCanceled) {
LogAppender.println("変換処理を中止しました : " + srcFile.getAbsolutePath());
return;
}
//kindlegen.exeがあれば実行
try {
if (kindlegen != null) {
long time = System.currentTimeMillis();
String outFileName = outFile.getAbsolutePath();
LogAppender.println("kindlegenを実行します : " + kindlegen.getName() + " \"" + outFileName + "\"");
ProcessBuilder pb = new ProcessBuilder(kindlegen.getAbsolutePath(), "-locale", "en", "-verbose", outFileName);
this.kindleProcess = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(this.kindleProcess.getInputStream()));
String line;
int idx = 0;
int cnt = 0;
String msg = "";
while ((line = br.readLine()) != null) {
if (line.length() > 0) {
System.out.println(line);
if (msg.startsWith("Error"))
msg += line;
else
msg = line;
if (idx++ % 2 == 0) {
if (cnt++ > 100) {
cnt = 1;
LogAppender.println();
}
LogAppender.append(".");
}
}
}
br.close();
if (convertCanceled) {
LogAppender.println("\n" + msg + "\nkindlegenの変換を中断しました");
} else {
if (outFileOrg != null) {
//mobiリネーム
File mobiTmpFile = new File(outFile.getAbsolutePath().substring(0, outFile.getAbsolutePath().length() - 4) + "mobi");
File mobiFile = new File(outFileOrg.getAbsolutePath().substring(0, outFileOrg.getAbsolutePath().length() - 4) + "mobi");
if (mobiFile.exists())
mobiFile.delete();
mobiTmpFile.renameTo(mobiFile);
if (outExt.endsWith(".epub")) {
//epubリネーム
if (outFileOrg.exists())
outFileOrg.delete();
outFile.renameTo(outFileOrg);
} else {
outFile.delete();
}
LogAppender.println("\n" + msg + "\nkindlegen変換完了 [" + (((System.currentTimeMillis() - time) / 100) / 10f) + "s] -> " + mobiFile.getName());
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (this.kindleProcess != null)
this.kindleProcess.destroy();
this.kindleProcess = null;
}
}
use of java.awt.image.BufferedImage in project AozoraEpub3 by hmdev.
the class ImageUtils method writeImage.
/** 大きすぎる画像は縮小して出力
* @param is 画像の入力ストリーム srcImageがあれば利用しないのでnull
* @param srcImage 読み込み済の場合は画像をこちらに設定 nullならisから読み込む
* @param zos 出力先Zipストリーム
* @param imageInfo 画像情報
* @param jpegQuality jpeg画質 (低画質 0.0-1.0 高画質)
* @param maxImagePixels 縮小する画素数
* @param maxImageW 縮小する画像幅
* @param maxImageH 縮小する画像高さ
* @param dispW 画面幅 余白除去後の縦横比補正用
* @param dispH 画面高さ 余白除去後の縦横比補正用
* @param autoMarginLimitH 余白除去 最大%
* @param autoMarginLimitV 余白除去 最大%
* @param autoMarginWhiteLevel 白画素として判別する白さ 100が白
* @param autoMarginPadding 余白除去後に追加するマージン */
public static void writeImage(InputStream is, BufferedImage srcImage, ZipArchiveOutputStream zos, ImageInfo imageInfo, float jpegQuality, LookupOp gammaOp, int maxImagePixels, int maxImageW, int maxImageH, int dispW, int dispH, int autoMarginLimitH, int autoMarginLimitV, int autoMarginWhiteLevel, float autoMarginPadding, int autoMarginNombre, float nombreSize) throws IOException {
try {
String ext = imageInfo.getExt();
int imgW = imageInfo.getWidth();
int imgH = imageInfo.getHeight();
int w = imgW;
int h = imgH;
imageInfo.setOutWidth(imgW);
imageInfo.setOutHeight(imgH);
//余白チェック時に読み込んだ画像のバッファ
byte[] imgBuf = null;
//回転とコントラスト調整なら読み込んでおく
if (srcImage == null && (imageInfo.rotateAngle != 0 || gammaOp != null))
srcImage = readImage(ext, is);
int[] margin = null;
if (autoMarginLimitH > 0 || autoMarginLimitV > 0) {
//1%
int startPixel = (int) (w * 0.01);
//3%
int ignoreEdge = (int) (w * 0.03);
//1%
int dustSize = (int) (w * 0.01);
//画像がなければ読み込み 変更なしの時にそのまま出力できるように一旦バッファに読み込む
if (srcImage == null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(is, baos);
imgBuf = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(imgBuf);
try {
srcImage = readImage(ext, bais);
} finally {
bais.close();
}
}
margin = getPlainMargin(srcImage, autoMarginLimitH / 100f, autoMarginLimitV / 100f, autoMarginWhiteLevel / 100f, autoMarginPadding / 100f, startPixel, ignoreEdge, dustSize, autoMarginNombre, nombreSize);
if (margin[0] == 0 && margin[1] == 0 && margin[2] == 0 && margin[3] == 0)
margin = null;
if (margin != null) {
//元画像が幅か高さかチェック
int mw = w - margin[0] - margin[2];
int mh = h - margin[1] - margin[3];
double dWH = dispW / (double) dispH;
double mWH = mw / (double) mh;
//縦横比で画面の横か縦に合わせる方向が変わらないようにマージンを調整する
if (w / (double) h < dWH) {
//元が縦
if (mWH > dWH && mw > dispW) {
//余白除去で横にはみ出す
mh = (int) (mw / dWH);
//下マージンを伸ばす
margin[3] = h - margin[1] - mh;
if (margin[3] < 0) {
margin[3] = 0;
margin[1] = h - mh;
}
}
} else {
//元が横
if (mWH < dWH && mh > dispH) {
//余白除去で縦にはみ出す
mw = (int) (mh * dWH);
double mLR = margin[0] + margin[2];
margin[0] = (int) ((w - mw) * margin[0] / mLR);
margin[2] = (int) ((w - mw) * margin[2] / mLR);
}
}
w = mw;
h = mh;
}
}
//倍率取得
double scale = 1;
//最大画素数指定
if (maxImagePixels >= 10000)
scale = Math.sqrt((double) maxImagePixels / (w * h));
//最大幅指定
if (maxImageW > 0)
scale = Math.min(scale, (double) maxImageW / w);
//最大高さ指定
if (maxImageH > 0)
scale = Math.min(scale, (double) maxImageH / h);
if (scale >= 1 && (gammaOp == null || srcImage.getType() == BufferedImage.TYPE_INT_RGB)) {
if (srcImage == null) {
//変更なしならそのままファイル出力
IOUtils.copy(is, zos);
} else {
if (margin == null && imgBuf != null && imageInfo.rotateAngle == 0) {
//余白除去が無く画像も編集されていなければバッファからそのまま出力
ByteArrayInputStream bais = new ByteArrayInputStream(imgBuf);
try {
IOUtils.copy(bais, zos);
} finally {
bais.close();
}
} else {
//編集済の画像なら同じ画像形式で書き出し 余白があれば切り取る
if (imageInfo.rotateAngle != 0) {
BufferedImage outImage = new BufferedImage(h, w, srcImage.getType());
Graphics2D g = outImage.createGraphics();
try {
g.setColor(Color.WHITE);
g.fillRect(0, 0, h, w);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
int x = 0;
int y = 0;
AffineTransform at;
if (imageInfo.rotateAngle == 90) {
at = AffineTransform.getQuadrantRotateInstance(1, 0, 0);
at.translate(0, -imgH);
if (margin != null) {
x = -margin[3];
y = -margin[0];
}
} else {
at = AffineTransform.getQuadrantRotateInstance(-1, 0, 0);
at.translate(-imgW, 0);
if (margin != null) {
x = -margin[1];
y = -margin[2];
}
}
AffineTransformOp ato = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
g.drawImage(srcImage, ato, x, y);
} finally {
g.dispose();
}
//入れ替え
srcImage = outImage;
} else if (margin != null)
srcImage = srcImage.getSubimage(margin[0], margin[1], srcImage.getWidth() - margin[2] - margin[0], srcImage.getHeight() - margin[3] - margin[1]);
if (gammaOp != null) {
BufferedImage filterdImage = new BufferedImage(srcImage.getWidth(), srcImage.getHeight(), BufferedImage.TYPE_INT_RGB);
srcImage = gammaOp.filter(srcImage, filterdImage);
srcImage = filterdImage;
}
_writeImage(zos, srcImage, ext, jpegQuality);
imageInfo.setOutWidth(srcImage.getWidth());
imageInfo.setOutHeight(srcImage.getHeight());
if (imageInfo.rotateAngle != 0)
LogAppender.println("画像回転" + ": " + imageInfo.getOutFileName() + " (" + h + "," + w + ")");
}
}
} else {
//縮小
int scaledW = (int) (w * scale + 0.5);
int scaledH = (int) (h * scale + 0.5);
if (imageInfo.rotateAngle != 0) {
scaledW = (int) (h * scale + 0.5);
scaledH = (int) (w * scale + 0.5);
}
//画像がなければ読み込み
if (srcImage == null)
srcImage = readImage(ext, is);
int imageType = srcImage.getType();
BufferedImage outImage;
ColorModel colorModel;
WritableRaster raster;
switch(gammaOp == null ? imageType : BufferedImage.TYPE_INT_RGB) {
case BufferedImage.TYPE_BYTE_BINARY:
colorModel = srcImage.getColorModel();
colorModel = getGray16ColorModel();
raster = colorModel.createCompatibleWritableRaster(scaledW, scaledH);
outImage = new BufferedImage(colorModel, raster, true, null);
break;
case BufferedImage.TYPE_BYTE_INDEXED:
colorModel = srcImage.getColorModel();
raster = colorModel.createCompatibleWritableRaster(scaledW, scaledH);
outImage = new BufferedImage(colorModel, raster, true, null);
break;
/*case BufferedImage.TYPE_BYTE_GRAY:
//PngEncoderのGRAYが薄くなるのでindexにする
colorModel = srcImage.getColorModel();
if (colorModel.getPixelSize() <= 4) colorModel = getGray16ColorModel();
else colorModel = getGray256ColorModel();
raster = colorModel.createCompatibleWritableRaster(scaledW, scaledH);
outImage = new BufferedImage(colorModel, raster, true, null);
break;*/
case BufferedImage.TYPE_BYTE_GRAY:
outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_BYTE_GRAY);
break;
case BufferedImage.TYPE_USHORT_GRAY:
outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_USHORT_GRAY);
break;
default:
outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);
}
Graphics2D g = outImage.createGraphics();
try {
if (imageType == BufferedImage.TYPE_BYTE_BINARY && imageType == BufferedImage.TYPE_BYTE_INDEXED && imageType == BufferedImage.TYPE_INT_ARGB) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, scaledW, scaledH);
}
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
int x = 0;
int y = 0;
if (imageInfo.rotateAngle == 0) {
if (margin != null) {
x = (int) (-margin[0] * scale + 0.5);
y = (int) (-margin[1] * scale + 0.5);
}
} else if (imageInfo.rotateAngle == 90) {
at.rotate(Math.toRadians(imageInfo.rotateAngle), 0, 0);
at.translate(0, -imgH);
if (margin != null) {
x = (int) (-margin[3] * scale + 0.5);
y = (int) (-margin[0] * scale + 0.5);
}
} else {
at.quadrantRotate(-1, 0, 0);
at.translate(-imgW, 0);
if (margin != null) {
x = (int) (-margin[1] * scale + 0.5);
y = (int) (-margin[2] * scale + 0.5);
}
}
AffineTransformOp ato = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
g.drawImage(srcImage, ato, x, y);
} finally {
g.dispose();
}
//コントラスト調整
if (gammaOp != null) {
BufferedImage filterdImage = new BufferedImage(outImage.getWidth(), outImage.getHeight(), BufferedImage.TYPE_INT_RGB);
outImage = gammaOp.filter(outImage, filterdImage);
outImage = filterdImage;
filterdImage = null;
//インデックス化
switch(imageType) {
case BufferedImage.TYPE_BYTE_BINARY:
colorModel = srcImage.getColorModel();
colorModel = getGray16ColorModel();
raster = colorModel.createCompatibleWritableRaster(scaledW, scaledH);
filterdImage = new BufferedImage(colorModel, raster, true, null);
break;
case BufferedImage.TYPE_BYTE_INDEXED:
colorModel = srcImage.getColorModel();
raster = colorModel.createCompatibleWritableRaster(scaledW, scaledH);
filterdImage = new BufferedImage(colorModel, raster, true, null);
break;
case BufferedImage.TYPE_BYTE_GRAY:
filterdImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_BYTE_GRAY);
break;
case BufferedImage.TYPE_USHORT_GRAY:
filterdImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_USHORT_GRAY);
break;
}
if (filterdImage != null) {
g = filterdImage.createGraphics();
try {
g.drawImage(outImage, 0, 0, null);
} finally {
g.dispose();
}
outImage = filterdImage;
}
}
_writeImage(zos, outImage, ext, jpegQuality);
imageInfo.setOutWidth(outImage.getWidth());
imageInfo.setOutHeight(outImage.getHeight());
if (scale < 1) {
LogAppender.append("画像縮小");
if (imageInfo.rotateAngle != 0)
LogAppender.append("回転");
LogAppender.println(": " + imageInfo.getOutFileName() + " (" + w + "," + h + ")→(" + scaledW + "," + scaledH + ")");
}
zos.flush();
}
} catch (Exception e) {
LogAppender.println("画像読み込みエラー: " + imageInfo.getOutFileName());
e.printStackTrace();
}
}
use of java.awt.image.BufferedImage in project hudson-2.x by hudson.
the class DependencyGraph method doGraph.
/**
* Experimental visualization of project dependencies.
*/
public void doGraph(StaplerRequest req, StaplerResponse rsp) throws IOException {
// Require admin permission for now (avoid exposing project names with restricted permissions)
Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
try {
// creates a dummy graphics just so that we can measure font metrics
BufferedImage emptyImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = emptyImage.createGraphics();
graphics.setFont(FONT);
final FontMetrics fontMetrics = graphics.getFontMetrics();
// TODO: timestamp check
Layout<AbstractProject> layout = new Layout<AbstractProject>(new Navigator<AbstractProject>() {
public Collection<AbstractProject> vertices() {
// only include projects that have some dependency
List<AbstractProject> r = new ArrayList<AbstractProject>();
for (AbstractProject p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
if (!getDownstream(p).isEmpty() || !getUpstream(p).isEmpty())
r.add(p);
}
return r;
}
public Collection<AbstractProject> edge(AbstractProject p) {
return getDownstream(p);
}
public Dimension getSize(AbstractProject p) {
int w = fontMetrics.stringWidth(p.getDisplayName()) + MARGIN * 2;
return new Dimension(w, fontMetrics.getHeight() + MARGIN * 2);
}
}, Direction.LEFTRIGHT);
Rectangle area = layout.calcDrawingArea();
// give it a bit of margin
area.grow(4, 4);
BufferedImage image = new BufferedImage(area.width, area.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setTransform(AffineTransform.getTranslateInstance(-area.x, -area.y));
g2.setPaint(Color.WHITE);
g2.fill(area);
g2.setFont(FONT);
g2.setPaint(Color.BLACK);
for (AbstractProject p : layout.vertices()) {
final Point sp = center(layout.vertex(p));
for (AbstractProject q : layout.edges(p)) {
Point cur = sp;
for (Point pt : layout.edge(p, q)) {
g2.drawLine(cur.x, cur.y, pt.x, pt.y);
cur = pt;
}
final Point ep = center(layout.vertex(q));
g2.drawLine(cur.x, cur.y, ep.x, ep.y);
}
}
int diff = fontMetrics.getAscent() + fontMetrics.getLeading() / 2;
for (AbstractProject p : layout.vertices()) {
Rectangle r = layout.vertex(p);
g2.setPaint(Color.WHITE);
g2.fillRect(r.x, r.y, r.width, r.height);
g2.setPaint(Color.BLACK);
g2.drawRect(r.x, r.y, r.width, r.height);
g2.drawString(p.getDisplayName(), r.x + MARGIN, r.y + MARGIN + diff);
}
rsp.setContentType("image/png");
ServletOutputStream os = rsp.getOutputStream();
ImageIO.write(image, "PNG", os);
os.close();
} catch (HeadlessException e) {
// not available. send out error message
rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
}
}
use of java.awt.image.BufferedImage in project hudson-2.x by hudson.
the class Graph method doPng.
/**
* Renders a graph.
*/
public void doPng(StaplerRequest req, StaplerResponse rsp) throws IOException {
if (req.checkIfModified(timestamp, rsp))
return;
try {
BufferedImage image = render(req, null);
rsp.setContentType("image/png");
ServletOutputStream os = rsp.getOutputStream();
ImageIO.write(image, "PNG", os);
os.close();
} catch (Error e) {
/* OpenJDK on ARM produces an error like this in case of headless error
Caused by: java.lang.Error: Probable fatal error:No fonts found.
at sun.font.FontManager.getDefaultPhysicalFont(FontManager.java:1088)
at sun.font.FontManager.initialiseDeferredFont(FontManager.java:967)
at sun.font.CompositeFont.doDeferredInitialisation(CompositeFont.java:254)
at sun.font.CompositeFont.getSlotFont(CompositeFont.java:334)
at sun.font.CompositeStrike.getStrikeForSlot(CompositeStrike.java:77)
at sun.font.CompositeStrike.getFontMetrics(CompositeStrike.java:93)
at sun.font.Font2D.getFontMetrics(Font2D.java:387)
at java.awt.Font.defaultLineMetrics(Font.java:2082)
at java.awt.Font.getLineMetrics(Font.java:2152)
at org.jfree.chart.axis.NumberAxis.estimateMaximumTickLabelHeight(NumberAxis.java:974)
at org.jfree.chart.axis.NumberAxis.selectVerticalAutoTickUnit(NumberAxis.java:1104)
at org.jfree.chart.axis.NumberAxis.selectAutoTickUnit(NumberAxis.java:1048)
at org.jfree.chart.axis.NumberAxis.refreshTicksVertical(NumberAxis.java:1249)
at org.jfree.chart.axis.NumberAxis.refreshTicks(NumberAxis.java:1149)
at org.jfree.chart.axis.ValueAxis.reserveSpace(ValueAxis.java:788)
at org.jfree.chart.plot.CategoryPlot.calculateRangeAxisSpace(CategoryPlot.java:2650)
at org.jfree.chart.plot.CategoryPlot.calculateAxisSpace(CategoryPlot.java:2669)
at org.jfree.chart.plot.CategoryPlot.draw(CategoryPlot.java:2716)
at org.jfree.chart.JFreeChart.draw(JFreeChart.java:1222)
at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1396)
at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1376)
at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1361)
at hudson.util.ChartUtil.generateGraph(ChartUtil.java:116)
at hudson.util.ChartUtil.generateGraph(ChartUtil.java:99)
at hudson.tasks.test.AbstractTestResultAction.doPng(AbstractTestResultAction.java:196)
at hudson.tasks.test.TestResultProjectAction.doTrend(TestResultProjectAction.java:97)
... 37 more
*/
if (e.getMessage().contains("Probable fatal error:No fonts found")) {
rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
return;
}
// otherwise let the caller deal with it
throw e;
} catch (HeadlessException e) {
// not available. send out error message
rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
}
}
Aggregations