Create thumbnails using PDFRenderer and ImgScalr

public static boolean createThumbnail(File inputFile, File targetFile)
{
try
{
BufferedImage img = null;
if (inputFile != null && targetFile != null && inputFile.getName().toLowerCase().endsWith(".pdf"))
{
img = convertPdfToImage(inputFile);
} else
{
img = ImageIO.read(inputFile);
}
BufferedImage thumbImg = createThumbnail(img);
ImageIO.write(thumbImg, "png", targetFile);
return true;
} catch (Exception e)
{

}
return false;
}

private static BufferedImage createThumbnail(BufferedImage img)
{
BufferedImage result = null;
if (img.getWidth() < img.getHeight())
{
result = resize(img, Method.QUALITY, Mode.FIT_TO_HEIGHT, 128, OP_ANTIALIAS);
} else
{
result = resize(img, Method.QUALITY, Mode.FIT_TO_WIDTH, 128, OP_ANTIALIAS);
}
return result;
}

private static BufferedImage convertPdfToImage(File pdfFile) throws IOException
{
RandomAccessFile raf = null;
FileChannel channel = null;
try
{
raf = new RandomAccessFile(pdfFile, "r");
channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
PDFPage page = pdffile.getPage(0);

Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
Image image = page.getImage(rect.width, rect.height, rect, null, true, true);
BufferedImage img = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
Graphics2D bufImageGraphics = img.createGraphics();
bufImageGraphics.drawImage(image, 0, 0, null);
return img;
} finally
{
if (channel != null)
{
channel.close();
}
if (raf != null)
{
raf.close();
}
}
}

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s