Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm looking for a free lib to convert from MS Word, WordPerfect and PDF to image.
Is anyone aware of any good, and up-to date JAVA library?
To convert PDF to images You can use PDFbox
Following is the code to convert PDF to images using pdfbox api
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageNode;
public List<String> generateImages(String pdfFile) throws IOException {
String imagePath = "/Users/$user/pdfimages/";
List <String> fileNames = new ArrayList<String>();
document = PDDocument.load(pdfFile); //// load pdf
node = document.getDocumentCatalog().getPages(); ///// get pages
List<PDPage> kids = node.getKids();
int count=0;
for(PDPage page : kids) { ///// iterate
BufferedImage img = page.convertToImage(BufferedImage.TYPE_INT_RGB,128);
File imageFile = new File(imagePath+ count++ + ".jpg");
ImageIO.write(img, "jpg", imageFile);
fileNames.add(imageFile.getName());
}
return fileNames;
}
Also another library ApachePOI can be used to convert PDF to Images
Here is the code sample
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;
public class JavaApplication12 {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream is = new FileInputStream(“D:/Presentation1.ppt”);
SlideShow ppt = new SlideShow(is);
is.close();
Dimension pgsize = ppt.getPageSize();
Slide[] slide = ppt.getSlides();
for (int i = 0; i < slide.length; i++) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, 1);
Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setColor(Color.white);
graphics.clearRect(0, 0, pgsize.width, pgsize.height);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// render
slide[i].draw(graphics);
// save the output
FileOutputStream out = new FileOutputStream(“slide-” + (i + 1) + “.png”);
javax.imageio.ImageIO.write(img, “png”, out);
out.close();
}
}
}
To convert MS Word to images you can have look at question posted here
Which uses JODConverter
JODConverter automates all conversions supported by OpenOffice.org, including
Any format to PDF
o OpenDocument (Text, Spreadsheet, Presentation) to PDF
o Word to PDF; Excel to PDF; PowerPoint to PDF
o RTF to PDF; WordPerfect to PDF; ...
And more
o OpenDocument Presentation (odp) to Flash; PowerPoint to Flash
o RTF to OpenDocument; WordPerfect to OpenDocument
o Any format to HTML (with limitations)
o Support for OpenOffice.org 1.0 and old StarOffice formats
//DOC to .jpeg
package org.doc;
import java.io.File;
import com.aspose.words.Document;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.SaveFormat;
public class DocToImage {
public static void main(String[] args) {
try {
String sourcePath = "D://G.doc";
Document doc = new Document(sourcePath);
ImageSaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);
options.setJpegQuality(100);
options.setResolution(100);
options.setUseHighQualityRendering(true);
for (int i = 0; i < doc.getPageCount(); i++) {
String imageFilePath = "E://"+ "images" + File.separator + "img_" + i + ".jpeg";
options.setPageIndex(i);
doc.save(imageFilePath, options);
}
System.out.println("Done...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*Here is the link from where we can download latest Aspose word jar.
http://www.aspose.com/java/word-component.aspx*/
//PDF to .png
package org.pdf;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
public class PdfToImage {
public static void main(final String[] args) throws Exception {
String storagePath = "E://dd.pdf";
//Image Save Directory
String realPathtopdfImageSaveDir = "E://uploads/";
RandomAccessFile raf = new RandomAccessFile(storagePath, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
int numPgs = pdffile.getNumPages();
for (int i = 0; i < numPgs; i++) {
PDFPage page = pdffile.getPage(i);
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
Image img = page.getImage(rect.width, rect.height, rect, null, true, true);
// save it as a file
BufferedImage bImg = toBufferedImage(img);
File yourImageFile = new File(realPathtopdfImageSaveDir +File.separator + "page_" + i + ".png");
ImageIO.write(bImg, "png", yourImageFile);
}
}
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
image = new ImageIcon(image).getImage();
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
System.out.println("The system does not have a screen");
}
if (bimage == null) {
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
Graphics g = bimage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
}
// jar required pdf-renderer.jar
Related
I have created pptx and ppt converter to images using apache poi but while converting some file i have an exception after two or three converts.
Exception in thread "main" java.lang.IllegalArgumentException: Color parameter outside of expected range: Red
Main converter from both pptx and ppt
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class Application {
public static void main(String[] args) throws Exception {
System.out.println("working");
String directory = System.getProperty("user.home") + "/Desktop/";
//creating an empty presentation
File file=new File(directory + "test6.pptx");
String fileName = file.getName();
// Identify the file whether it is ppt or pptx
String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
FileInputStream inputStream = new FileInputStream(directory + fileName);
if (extension.equals("pptx")) {
XMLSlideShow pptx = new XMLSlideShow(inputStream);
//getting the dimensions and size of the slide
Dimension pgsize = pptx.getPageSize();
java.util.List<XSLFSlide> pptxSlide = Arrays.asList(pptx.getSlides());
for (int i = 0; i < pptxSlide.size(); i++) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height,BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = createImage(img, pgsize);
//render
pptxSlide.get(i).draw(graphics);
graphics.setComposite(AlphaComposite.DstOver);
graphics.setPaint(Color.WHITE);
//creating an image file as output
imageFile(i, img);
graphics.dispose();
}
}else if(extension.equals("ppt")){
SlideShow ppt = new SlideShow(inputStream);
//getting the dimensions and size of the slide
Dimension pgsize = ppt.getPageSize();
List<Slide> slide = Arrays.asList(ppt.getSlides());
for (int i = 0; i < slide.size(); i++) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height,BufferedImage.TYPE_INT_RGB);
//render
slide.get(i).draw(createImage(img, pgsize));
//creating an image file as output
imageFile(i, img);
}
}else {
throw new Exception("Not compatible type ");
}
}
private static void imageFile(int i, BufferedImage img) throws IOException {
FileOutputStream out = new FileOutputStream("ppt_image_" + i + ".png");
javax.imageio.ImageIO.write(img, "png", out);
System.out.println("Image successfully created");
out.close();
}
private static Graphics2D createImage(BufferedImage img, Dimension pgsize){
Graphics2D graphics = img.createGraphics();
//clear the drawing area
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// default rendering options
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setComposite(AlphaComposite.DstOver);
return graphics;
}
}
The main problem is that I want to convert any pptx file any kind of with gradient or simple colors to images.
Converted gradient slide [greyed]
I am trying to write a simple code to write a red 100x100 jpg
For some reason the colors are not right,
I am only setting the color RED :
renderdImg.setRGB(x, y, Color.RED.getRGB());
but the fnal image comes out purplish, what am I doing wrong?
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageWriter {
public static void main(String[] args) throws IOException {
String fileName = "red_100.jpg";
String filePath = "c:\\temp\\";
int width = 100;
int height = 100;
BufferedImage renderdImg = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
for(int x=0;x< width; x++) {
for(int y=0;y<height; y++) {
renderdImg.setRGB(x, y, Color.RED.getRGB());
}}
File fileToWrite = new File(filePath + fileName);
ImageIO.write(renderdImg, "jpg", fileToWrite);
}
}
Set the image type to BufferedImage.TYPE_INT_RGB and it should become reddish:
BufferedImage renderdImg = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
please i need help
I am trying to convert image .dcm to grayscale in java but i couldn't.
i wan't to know how to read image.dcm in java and convert it to grayscale.
note :: this code is already run for image .jpg,.png
package otsuthresholding;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
public class OtsuThresholding {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME );
File input = new File("p.dcm");
BufferedImage image = ImageIO.read(input);
byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
mat.put(0, 0, data);
Mat mat1 = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC1);
Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY);
byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int)(mat1.elemSize())];
mat1.get(0, 0, data1);
BufferedImage image1 = new BufferedImage(mat1.cols(),mat1.rows(), BufferedImage.TYPE_BYTE_GRAY);
image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1);
File ouptut = new File("grayscale.dcm");
ImageIO.write(image1, "dcm", ouptut);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
I got the video stream from cctv camera using opencv. Now I want to detect a simple motion / object from this video stream. For example, if any person come in any selected zone then rectangular border should be generated around him. I search some opencv tutorial, but I didn't got any proper solution or idea.I used the following code to display video stream.
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
public class VideoStream
{
static BufferedImage tmpImg=null;
public static void main(String args[]) throws InterruptedException
{
System.out.println("opencv start..");
// Load native library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture camView=new VideoCapture();
camView.open("http://192.168.1.7:80/cgi-bin/view.cgi?chn=6&u=admin&p=");
if(!camView.isOpened())
{
System.out.println("Camera Error..");
}
else
{
System.out.println("Camera successfully opened");
}
videoCamera cam=new videoCamera(camView);
//Initialize swing components
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(cam);
frame.setSize(1024,768);
frame.setVisible(true);
while(camView.isOpened())
{
cam.repaint();
}
}
}
#SuppressWarnings("serial")
class videoCamera extends JPanel
{
VideoCapture camera;
Mat mat=new Mat();
public videoCamera(VideoCapture cam)
{
camera = cam;
}
public BufferedImage Mat2BufferedImage(Mat m)
{
int type = BufferedImage.TYPE_BYTE_GRAY;
if (m.channels() > 1)
{
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels() * m.cols() * m.rows();
byte[] b = new byte[bufferSize];
m.get(0, 0, b); // get all the pixels
BufferedImage img = new BufferedImage(m.cols(), m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return img;
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Mat mat = new Mat();
camera.read(mat);
BufferedImage image = Mat2BufferedImage(mat);
g.drawImage(image,0,0,image.getWidth(),image.getHeight(), null);
}
}
Can any one knows how could we do that.
please check this code, but i implement it by python
import cv2, time, pandas
from datetime import datetime
first_frame = None
status_list = [None,None]
times = []
df=pandas.DataFrame(columns=["Start","End"])
video = cv2.VideoCapture('rtsp://admin:Paxton10#10.199.27.128:554')
while True:
check, frame = video.read()
status = 0
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray,(21,21),0)
if first_frame is None:
first_frame=gray
continue
delta_frame=cv2.absdiff(first_frame,gray)
thresh_frame=cv2.threshold(delta_frame, 30, 255, cv2.THRESH_BINARY)[1]
thresh_frame=cv2.dilate(thresh_frame, None, iterations=2)
(cnts,_)=cv2.findContours(thresh_frame.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in cnts:
if cv2.contourArea(contour) < 200000:
continue
status=1
(x, y, w, h)=cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0,255,0), 3)
status_list.append(status)
status_list=status_list[-2:]
if status_list[-1]==1 and status_list[-2]==0:
times.append(datetime.now())
if status_list[-1]==0 and status_list[-2]==1:
times.append(datetime.now())
#cv2.imshow("Gray Frame",gray)
#cv2.imshow("Delta Frame",delta_frame)
imS = cv2.resize(thresh_frame, (640, 480))
cv2.imshow("Threshold Frame",imS)
imS = cv2.resize(frame, (640, 480))
cv2.imshow("Color Frame",imS)
#cv2.imshow("Color Frame",frame)
key=cv2.waitKey(1)
if key == ord('q'):
if status == 1:
times.append(datetime.now())
break
print(status_list)
print(times)
for i in range(0, len(times), 2):
df = df.append({"Start": times[i],"End": times[i+1]}, ignore_index=True)
df.to_csv("Times.csv")
video.release()
cv2.destroyAllWindows
This question already has answers here:
decrease image resolution in java
(4 answers)
Closed 8 years ago.
can any one help me..?
I have some .jpg's created from JPanel. Unfortunately its DPI is 72. Is there a programmatic way to change the DPI of these .jpg's ?
Now i use following code for change DPI. But it have some issues when i try to build project.
`JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(outfile));
JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
jpegEncodeParam.setXDensity(300);
jpegEncodeParam.setYDensity(300);
jpegEncoder.encode(image, jpegEncodeParam);`
Thanks in advance :)
You can scale an image using Graphics2D methods (from java.awt). This tutorial at http://www.mkyong.com/java/how-to-resize-an-image-in-java explains it in depth.
here is an example
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.FileImageInputStream;
import javax.swing.ImageIcon;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImageManipulation {
public static void main(String[] args) throws Exception {
File infile = new File("/your image.jpg");
File outfile = new File("/your image.jpg");
ImageReader reader = ImageIO.getImageReadersByFormatName("jpeg").next();
reader.setInput(new FileImageInputStream(infile), true, false);
IIOMetadata data = reader.getImageMetadata(0);
BufferedImage image = reader.read(0);
int w = 600, h = -1;
Image rescaled = image.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING);
BufferedImage output = toBufferedImage(rescaled, BufferedImage.TYPE_INT_RGB);
Element tree = (Element) data.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
for (int i = 0; i < jfif.getAttributes().getLength(); i++) {
Node attribute = jfif.getAttributes().item(i);
System.out.println(attribute.getNodeName() + "="
+ attribute.getNodeValue());
}
FileOutputStream fos = new FileOutputStream(outfile);
JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(fos);
JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(output);
jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
jpegEncodeParam.setXDensity(300);
jpegEncodeParam.setYDensity(300);
jpegEncoder.encode(output, jpegEncodeParam);
fos.close();
}
public static BufferedImage toBufferedImage(Image image, int type) {
int w = image.getWidth(null);
int h = image.getHeight(null);
BufferedImage result = new BufferedImage(w, h, type);
Graphics2D g = result.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return result;
}
}
There is a similar question about resolution, answered in the following SO question here.
In general, you may be interested in learning image processing algorithms, which are described here:
The basic concept in decreasing resolution is that you are selectively
deleting data from the image.