How to change JPEG image DPI using java [duplicate] - java

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.

Related

Image To Stencil in Java

I am new to image processing in java and I am trying to convert an image to stencil (I think stencil is name given for it!).
The input image is this:-
After processing the image would be like this:-
I searched google. But could find a solution. (maybe because I don't know what is the actual name of this process.)
Is this possible with java?
Yes I found the solution. if we Binarize an image it will work.
Input image:-
Output Image:-
Code:-
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Main {
public static void main(String[] args) throws IOException {
BufferedImage bi = ImageIO.read(new File("D:\\IMG_20211029_124954.jpg"));
ImageIO.write(binarizeImage(bi), "png", new File("D:\\1.png"));
}
public static BufferedImage binarizeImage(BufferedImage img_param)
{
BufferedImage image = new BufferedImage(
img_param.getWidth(),
img_param.getHeight(),
BufferedImage.TYPE_BYTE_BINARY
);
Graphics g = image.getGraphics();
g.drawImage(img_param, 0, 0, null);
g.dispose();
return image;
}
}
To make the image transparent , You can do something like this:-
for(int i=0;i<img.width;i++){
for(int j=0;j<img.height;j++){
Color c = new Color(255,255,255,0);
if(img.getRGB==Color.white.getRGB){
img.setRGB(i,j,c.getRGB)
}
}
}

How To Convert Image .dcm to Graycale in Java

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());
}
}
}

Java - Motion / Object detection (Human detection) using OpenCV

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

Java MS Word and PDF conversion to image (png/jpg) [closed]

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

Manipulating a colored image in matrix form in java

I am working on a project related to colored image manipulation using JAVA.
I got to know the conversion of the colored image into a matrix using a getSample method of Raster class,
pixels[x][y]=raster.getSample(x,y,0);
I got the matrix in pixels[][] (only the values in red band).
Then i converted the matrix back to image using WritableRaster as,
raster.setSample(i,j,0,pixels[i][j]);
I converted it to image using,
*BufferedImage image=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
image.setData(raster);*
But the problem is,
1) I want the colored image to be displayed as it is whereas i am getting only a particular band(like only red, only blue . . ) because I have to specify a band as per the prototype of the method setSample and getenter code hereSample.
2) How can i get a 2d matrix representing a colored image(of all 3 bands represented in 3 different matrices)
Here is the code that i wrote with the help of snippets of code online...
import java.awt.Image;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
class TestImage {
ImageIcon icon;
SampleModel sampleModel;
public static void main(String args[]){
TestImage mamu = new TestImage();
File file = new File("photo.jpg");
mamu.compute(file);
}
public void compute(File file){
try{
BufferedImage img= ImageIO.read(file);
Raster raster=img.getData();
sampleModel = raster.getSampleModel();
int w=raster.getWidth(),h=raster.getHeight();
int pixels[][]=new int[w][h];
for (int x=0;x<w;x++){
for(int y=0;y<h;y++){
pixels[x][y]=raster.getSample(x,y,0);
}
}
Image image = getImage(pixels);
JFrame frame = new JFrame("uff");
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
frame.setContentPane(label);
frame.setVisible(true);
frame.setSize(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}catch (Exception e){
e.printStackTrace();
}
}
public java.awt.Image getImage(int pixels[][]){
int w=pixels.length;
int h=pixels[0].length;
WritableRaster raster= Raster.createWritableRaster(sampleModel, new Point(0,0));
for(int i=0;i<w;i++){
for(int j=0;j<h;j++){
raster.setSample(i,j,0,pixels[i][j]);
}
}
BufferedImage image=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
image.setData(raster);
File output=new File("check.jpg");
try {
ImageIO.write(image,"jpg",output);
}catch (Exception e){
e.printStackTrace();
}
return image;
}
}
You may be looking or java.awt.image.LookupOp, which uses a java.awt.image.LookupTable to modify bands en bloc. Several examples are cited here. The image below illustrates inversion:
short[] invert = new short[256];
for (int i = 0; i < 256; i++) {
invert[i] = (short) (255 - i);
}
BufferedImageOp invertOp = new LookupOp(new ShortLookupTable(0, invert), null));
invertOp.filter(src, dst);

Categories

Resources