I have to build a Java servlet that receives an image and returns that image converted to PNG format. How can I achieve this?
By converting I don't mean changing the file extension, like some examples suggest.
Thanks in advance!
Try this out:
package demo;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main( String [] args ) throws IOException {
File input = new File("input.gif");
File output = new File("output.png");
ImageIO.write( ImageIO.read( input ), "png", ouput);
}
}
Read ImageIO.
Of course, you may want to read and write from an stream instead.
ImageIO.write(ImageIO.read(new File("img.gif")), "png", new File("img.png"));
Use ImageIo to save an Image in any format your want.
Related
I am trying to convert the image to a searchable pdf using tesseract. The below command line option working fine for me.
Exploring a similar option in java. But not sure what to pass in the arguments. Below is my java code
import java.io.File;
import java.util.Arrays;
import java.util.List;
import net.sf.saxon.expr.instruct.ValueOf;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class Mask2 {
public static void main(String[] args) {
File image = new File("D:\\ML\\Java\\img3.PNG");
Tesseract tesseract = new Tesseract();
tesseract.setDatapath("C://Program Files//Tesseract-OCR//tessdata");
tesseract.setLanguage("eng");
tesseract.setPageSegMode(1);
tesseract.setOcrEngineMode(1);
try {
// Not sure what to pass in arguments
tesseract.createDocumentsWithResults()
} catch (TesseractException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Any Suggestions / Solutions would be much helpful.
you can create a list of renderFormats like this ( you can add others)
List<RenderedFormat> renderFormats = new ArrayList<RenderedFormat>();
renderFormats.add(RenderedFormat.PDF);
and then you can pass the path of the input filename (PDF or IMG), the path of the output filename with no extension, and the render format you want to use.
tesseract.createDocuments("a/b/c/inputfile.PNG", "a/b/c/outputfile", renderFormats);
Ciao!
I have an image in a directory.
I want to make a copy of that image with a different name without doing harm to the original image in the same directory.
So there will be two same images in one folder with a different name.
I want a basic code like I tried -
File source = new File("resources/"+getImage(0));
File dest = new File("resources/");
source.renameTo("resources/"+getImage(0)+);
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
When I upload the same image to the Amazon server multiple times in automation and then it starts giving issue to upload.
So we want to upload a mirror copy of image everytime.
In eclipse generally have resources folder. I want to make copy of a original image every-time before we upload and delete it after upload.
Kindly suggest some approach
You can just copy the file and use StandardCopyOption.COPY_ATTRIBUTES
public static final StandardCopyOption COPY_ATTRIBUTES
Copy attributes to the new file.
Files.copy(Paths.get(//path//to//file//and//filename),
Paths.get(//path//to//file//and//newfilename), StandardCopyOption.COPY_ATTRIBUTES);
Not a perfect solution, but Instead of handling pop-up box we can directly force file path into the form: [I have used date-stamp for creating new filenames but some different logic could also be used viz- Random String appender etc.]
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Upload {
private static final String SRC_RESOURCES_FILE_PATH = System.getProperty("user.dir")+"/src/resources/";
File s1 = new File(SRC_RESOURCES_FILE_PATH+"Img1.png");
File s2 = new File(SRC_RESOURCES_FILE_PATH+"Img"+getDateStamp()+".png");
#Test
public void uploadFunction() throws IOException {
copyFileUsingJava7Files(s1,s2);
}
private String getDateStamp(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date).toString();
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}
There is a web site developed entirely in PHP with GD library that mainly deals with printing text over a random image.
The text has to be printed in any of about 100 prescribed TTF fonts (residing in a directory near the .php files) in a dozen of prescribed colors and there is a requirement to specify location of the text according to any of several prescribed algorithms.
This is solved by using imagettfbox() which returns geometry of the text, which is then mapped onto the image using imagettftext().
What can I use in Java to achieve the same functionality with servlets/beans?
I can put the TTF fonts anywhere I have to. Registering them in Windows is undesirable, but if that's the only option we'd go for it (currently they are not).
#LexLythius:
From your link and some other resources I pieced together a working solution to drawing text over graphics:
// file is pointed at the image
BufferedImage loadedImage = ImageIO.read(file);
// file is pointed at the TTF font
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
Font drawFont = font.deriveFont(20); // use actual size in real life
Graphics graphics = loadedImage.getGraphics();
FontMetrics metrics = graphics.getFontMetrics(drawFont);
Dimension size = new Dimension(metrics.getHeight(), metrics.stringWidth("Hello, world!"));
graphics.setFont(drawFont);
graphics.setColor(new Color(128, 128, 128); // use actual RGB values in real life
graphics.drawString("Hello, world!", 10,10); // use Dimension to calculate position in real life
What is remaining is displaying that image in a servlet and deciding what functionality goes where - to a servlet or bean.
You can get an OutputStream from the servlet response, and pass that OutputStream to ImageIO.write. Example based on the code from here (not my code):
http://www.avajava.com/tutorials/lessons/how-do-i-return-an-image-from-a-servlet-using-imageio.html
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg"); // change this if you are returning PNG
File f = new File( /* path to your file */ );
BufferedImage bi = ImageIO.read(f);
// INSERT YOUR IMAGE MANIPULATION HERE
OutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out); // or "png" if you prefer
out.close(); // may not be necessary; containers should do this for you
}
Depending on how much memory you have, pre-loading the fonts and keeping a pool of them may save a bit of time.
I was able to successfully play video with Xuggler with the code below. I need to be able to stream from an inputStream instead of a file. I tried using the commented out code to create an Icontainer. I did modified the getTestFile method to use a String instead of an inputstream when I commented out the code. It was originally getting the inputstream correctly.
When I call open on Icontainer is just blocks indefinitely. I don't know if I'm approaching this correctly. How would I do basically the same thing but without use a file and using an input stream?
Thanks :-)
package com.plumber.testing;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.IMediaViewer;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.xuggler.IContainer;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class VideoTest {
public static void main(String[] args) throws FileNotFoundException {
// IContainer iContainer = IContainer.make();
// iContainer.open(getTestFile("IMG_0983.MOV"), null);
// I was originally passing the icontainer to make reader
IMediaReader mediaReader = ToolFactory.makeReader(getTestFile("IMG_0983.MOV"));
IMediaViewer mediaViewer = ToolFactory.makeViewer(true);
mediaReader.addListener(mediaViewer);
while (mediaReader.readPacket() == null) ;
}
private static String getTestFile(String fileName) {
return VideoTest.class.getClassLoader().getResource("com/plumber/testing/testfiles/" + fileName).getPath();
}
}
I think you need to do something like this:
IContainer iContainer = IContainer.make();
if (iContainer.open(inputStream, IContainer.Type.READ, format) >= 0) {
IMediaReader mediaReader = ToolFactory.makeReader(iContainer);
...
}
... based on what the javadocs say. It looks like the format needs to be obtained using static methods of the IContainerFormat class. If you supply a null format, the open method will attempt to guess the container type ... apparently.
I want to convert several .jpg files (taken using the device camera) to ONE .pdf file.
I saw a lot of tools like iText, mupdf, PDFjet, pdjBox.
Is there something more simple? (like an API ready for android?)
Thanks.
using iText Library to convert the text to pdf. Use this to convert image to pdf.
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class imagesPDF
{
public static void main(String arg[])throws Exception
{
Document document=new Document();
PdfWriter.getInstance(document,new FileOutputStream("YourPDFHere.pdf"));
document.open();
Image image = Image.getInstance ("yourImageHere.jpg");
document.add(new Paragraph("Your Heading for the Image Goes Here"));
document.add(image);
document.close();
}
}