Is it possible to generate a new image name for each image that is processed using the following code (I have highlighted the relevant section)?
public static void makeBinary(File image) {
try{
//Read in original image.
BufferedImage inputImg = ImageIO.read(image);
//Obtain width and height of image.
double image_width = inputImg.getWidth();
double image_height = inputImg.getHeight();
//New images to draw to.
BufferedImage bimg = null;
BufferedImage img = inputImg;
//Draw the new image.
bimg = new BufferedImage((int)image_width, (int)image_height, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
// ************* THIS IS WHERE I AM HAVING DIFFICULTY ***************
//Save new binary (output) image.
String temp = "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);
// ******************************************************************
}
catch (Exception e){
System.out.println(e);
}
}
I have 300 images, numbered 001.jpg - 300.jpg, and what I would like is for each new outputted image to be named something along the lines of, binary_001.jpg - binary_300.jpg.
The method that calls makeBinary() is located in another class and is:
public static void listFiles() {
File dir = new File("images");
File imgList[] = dir.listFiles();
if(dir.isDirectory()){
for(File img : imgList){
if(img.isFile()){
MakeBinary.makeBinary(img);
System.out.println(img + ": processed successfully.");
}
else{
System.out.println("Directory detected; skipping to next file,");
}
}
}
}
How can I go about achieving this?
Many thanks.
Get the filename from your File image parameter and add it to the new filename:
String temp = image.getName() + "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);
You can just concatenate name from the original image (in your code 'image' you pass to ImageIO with the string "_inverted", this way you would have original name for each image you process: image.jpg -> image_inverted.jpg
File fi = new File("images\\" + "binary_" + image.getName());
Should do the trick.
Or even better:
File fi = new File(image.getParent(), "binary_" + image.getName());
Related
I'm searching a method with JRGraphics2DExporter to export report as JPG.
Is there any kind of possibility to do that with JRGraphics2DExporter?
You want to use the JRGraphics2DExporter, but this can also be done directly using the JasperPrintManager
Example of code contemplenting multiple images 1 for every page
//Get my print, by filling the report
JasperPrint jasperPrint = JasperFillManager.fillReport(report, map,datasource);
final String extension = "jpg";
final float zoom = 1f;
String fileName = "report";
//one image for every page in my report
int pages = jasperPrint.getPages().size();
for (int i = 0; i < pages; i++) {
try(OutputStream out = new FileOutputStream(fileName + "_p" + (i+1) + "." + extension)){
BufferedImage image = (BufferedImage) JasperPrintManager.printPageToImage(jasperPrint, i,zoom);
ImageIO.write(image, extension, out); //write image to file
} catch (IOException e) {
e.printStackTrace();
}
}
If you like 1 image with all the pages, you should set the isIgnorePagination="true" on the jasperReport tag
You could instruct to the exporter in order to dump the report to an image in memory and then save it to disk.
Create the image (set the proper width, height and format):
BufferedImage image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
Create the exporter, configure it (maybe some other parameters should be set) and export the report:
JRGraphics2DExporter exporter = new JRGraphics2DExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, (Graphics2D)image.getGraphics());
exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, Float.valueOf(1));
exporter.exportReport();
Dump the image to disk:
ImageIO.write(image, "PNG", new File("image.png"));
I am trying to merge two TIFF images which are in form of FileInputStream into a single Tiff image. Although the image is getting merged the output file is coming up as Black. While comparing the original image and the converted image I could see that the bit depth of the converted image changes to 1. Could anybody provide a solution to this?
The code that I am using is:
public class MergerTiffUsingBuffer {
public static void main(String[] args) {
File imageFile1 = new File("D:/Software/pdfbox-1.3.1.jar/tiff/FLAG_T24.TIF");
File imageFile2 = new File("D:/Software/pdfbox-1.3.1.jar/tiff/CCITT_3.TIF");
try {
FileInputStream fis1 = new FileInputStream(imageFile1);
FileInputStream fis2 = new FileInputStream(imageFile2);
List<BufferedImage> bufferedImages=new ArrayList<>();
List<FileInputStream> inputStreams=new ArrayList<>();
inputStreams.add(fis1);
inputStreams.add(fis2);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("tiff");
ImageReader reader = (ImageReader) readers.next();
for(FileInputStream inputStream:inputStreams){
ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
reader.setInput(iis);
ImageReadParam param = reader.getDefaultReadParam();
Image image = reader.read(0, param);
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
OutputStream out = new FileOutputStream("D:/Software/pdfbox-1.3.1.jar/tiff/MergedTiff.TIF");
BufferedImage binarized = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
ImageIO.write(binarized, "tiff", out);
bufferedImages.add(bufferedImage);
}
System.out.println(bufferedImages.size());
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
You seem to be a little confused about how to copy image data. Simply creating a new, blank image, by passing the dimensions of another image, will not copy it... So a fully black image is what I would expect after running your code.
Replace your for loop with something like this:
for (FileInputStream inputStream : inputStreams) {
ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
reader.setInput(iis);
BufferedImage image = reader.read(0, null); // a) BufferedImage is returned! b) null param is fine!
BufferedImage binarized = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
// The following 7 lines is the important part you were missing:
Graphics2D g = binarized.createGraphics();
try {
g.drawImage(image, 0, 0, null);
}
finally {
g.dispose();
}
OutputStream out = new FileOutputStream("D:/Software/pdfbox-1.3.1.jar/tiff/MergedTiff.TIF");
ImageIO.write(binarized, "tiff", out); // You probably want to check return value (true/false)!
bufferedImages.add(image);
}
Capture a image from the clipboard whenever Print screen is pressed and save it in a file (.doc) using java
Main aim is to copy the data from the clipboard and automatically save it into local disk without going to the desired program (i.e MS Word)- click new - pressing (Ctrl+V) to paste and save it with a name.
The code should perform all of the above three steps automatically.
My Source Code
public class CaptureScreenShot {
private static String DIR ="C:\\QUIS\\";
private static JTextField txtDocNumber;
public static void main(String[] args) throws Exception{
txtDocNumber = new JTextField();
Robot robot = new Robot();
Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
int width = (int) d.getWidth();
int height = (int) d.getHeight();
robot.delay(5000);
Image image = robot.createScreenCapture(new Rectangle(0, 0, width,
height));
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
String fileNameToSaveTo = "C:/QUIS/screenCapture_" + createTimeStampStr() + ".PNG";
String newFile = "C:/QUIS/x" + ".org";
File newFilee = new File(newFile);
writeImage(bi, fileNameToSaveTo, "PNG");
System.out.println("Screen Captured Successfully and Saved to:\n"+fileNameToSaveTo);
Desktop desktop = Desktop.getDesktop();
writeImage(bi, newFile, "org");
desktop.open(newFilee);
}
public static int writeImage(BufferedImage img, String fileLocation,
String extension) {
try {
BufferedImage bi = img;
File outputfile = new File(fileLocation);
ImageIO.write(bi, extension, outputfile);
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
public static String createTimeStampStr() throws Exception {
Calendar mycalendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss");
String timeStamp = formatter.format(mycalendar.getTime());
return timeStamp;
}
}
If you are not particular about a java code, you could use some screen capture tool instead. Snagit is a good tool. You could find it on http://www.techsmith.com/snagit.html
Try this sample code, according to your question it will copy contents from clipboard and will generate image file
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
try {
//Get data from clipboard and assign it to an image.
//clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
BufferedImage image = (BufferedImage)clipboard.getData(DataFlavor.imageFlavor);
//file that we'll save to disk.
File file = new File("image.jpg");
//class to write image to disk. You specify the image to be saved, its type,
// and then the file in which to write the image data.
ImageIO.write(image, "jpg", file);
}
I'm getting heap space error/ out of memory exception.
I'm trying to generate a PDF using iText and converting the PDF to jpg image using aspose api. The PDF which is being generated is of 3 pages, I'm converting that PDF to image page by page and stitching them together into one jpg image. This code is working fine in my local development machine, but getting exception when move to test server.
The code which I'm using for this is:
public void silSignedPDF(AgreementBean agBean,String sourceTemplatePDFURL, Hashtable<String, String> val, String destinationPDFPath) throws IOException, DocumentException, SQLException{
String methodName = "silSignedPDF";
LogTracer.writeDebugLog(className, methodName, "Start");
String serverPath = System.getProperty("jboss.server.home.dir");
String sourceTemplatePDFURL1 = serverPath+AppConstants.PDL_Agreement_Template +"/Online_Installment_Agreement.pdf";
System.out.println("sourceTemplatePDFURL1 "+sourceTemplatePDFURL1);
File f = new File(sourceTemplatePDFURL1);
InputStream sourceTemplatePDFUrlStream = new BufferedInputStream(new FileInputStream(f));
File destinationFile = new File(destinationPDFPath+"/"+agBean.getDealNbr()+".pdf");
PdfReader reader = new PdfReader(sourceTemplatePDFUrlStream);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
destinationFile));
AcroFields form = stamper.getAcroFields();
Enumeration enumeration = val.keys();
// iterate through Hashtable val keys Enumeration
while (enumeration.hasMoreElements()) {
String nextElement = (String) enumeration.nextElement();
String nextElementValue = (String) val.get(nextElement);
form.setField(nextElement, nextElementValue);
}
stamper.setFormFlattening(true);
stamper.close();
PdfConverter pdf = new PdfConverter();
pdf.bindPdf(destinationPDFPath+"/"+agBean.getDealNbr()+".pdf");
try {
pdf.doConvert();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//set start and end pages
pdf.setStartPage(1);
pdf.setEndPage(1);
//initialize conversion process
//convert pages to images
String suffix = ".jpg";
int imageCount = 1;
while (pdf.hasNextImage())
{
try {
pdf.getNextImage(destinationPDFPath+"/"+agBean.getDealNbr()+"_"+imageCount + suffix,ImageType.JPEG);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageCount++;
}
/* PDFImages pdfDoc = new PDFImages (destinationPDFPath+"/"+agBean.getDealNbr()+".pdf", null);
for (int count = 0; count < pdfDoc.getPageCount(); ++count)
{
pdfDoc.savePageAsJPEG(count,destinationPDFPath+"/"+agBean.getDealNbr()+"_"+count + ".png", 150, 0.8f);
}*/
File file1 = new File(destinationPDFPath+"/"+agBean.getDealNbr()+"_1" + ".jpg");
File file2 = new File(destinationPDFPath+"/"+agBean.getDealNbr()+"_2" + ".jpg");
File file3 = new File(destinationPDFPath+"/"+agBean.getDealNbr()+"_3" + ".jpg");
BufferedImage img1 = ImageIO.read(file1);
BufferedImage img2 = ImageIO.read(file2);
BufferedImage img3 = ImageIO.read(file3);
int widthImg1 = img1.getWidth();
int heightImg1 = img1.getHeight();
int heightImg2 = img2.getHeight();
int heightImg3 = img3.getHeight();
BufferedImage img = new BufferedImage(
widthImg1,
heightImg1+heightImg2+heightImg3,
BufferedImage.TYPE_INT_RGB);
img.createGraphics().drawImage(img1, 0, 0, null);
img.createGraphics().drawImage(img2, 0, heightImg1, null);
img.createGraphics().drawImage(img3, 0, heightImg1+heightImg2, null);
File final_image = new File(destinationPDFPath+"/"+agBean.getDealNbr() + ".jpg");
ImageIO.write(img, "png", final_image);
file1.delete();
file2.delete();
file3.delete();
LogTracer.writeDebugLog(className, methodName, "End");
}
Heap size should be changed for your JVM, but dont change it to any random number. Heap size should be modified based on the memory that is used by your system. You can check this for further specification.
Page to Image conversion using Aspose.Pdf required more memory than the default. Run the program with at least 512 MB memory (-Xmx512m).
Is it possible to feed an array of image names into code which converts images to greyscale?
I am able to convert an image into greyscale by using this code:
public static void makeGrey() {
try{
//Read in original image.
BufferedImage image = ImageIO.read(new File("images\\012.jpg"));
//Obtain width and height of image.
double image_width = image.getWidth();
double image_height = image.getHeight();
BufferedImage bimg = null;
BufferedImage img = image;
//Draw the new image.
bimg = new BufferedImage((int)image_width, (int)image_height, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
//Save new greyscale (output) image.
String temp = "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);
}
catch (Exception e){
System.out.println(e);
}
}
However, this code only works on a single file at a time and I would like to know how to go about getting it to work through all files located in the images directory?
I have created an array which goes through the images directory and stores the names of all of the files and I would like to know how to pass these filenames into my makeGrey() method?
static File dir = new File("images");
static File imgList[] = dir.listFiles();
public static void listFiles(String imageName) {
if(dir.isDirectory()){
for(File img : imgList){
if(img.isFile()){
MakeGrey.makeGrey();
}
}
}
Thank you.
Your makeGray() method should look like this:
public static void makeGrey(File image) {
try{
//Read in original image.
BufferedImage inputImage = ImageIO.read(image);
...
...
//Save new greyscale (output) image. (Or you'll rewrite same image all the time...)
File fi = new File("images\\inverted_" + image.getName()
...
...
and other part of the code should call it like this:
static File dir = new File("images");
static File imgList[] = dir.listFiles();
public static void listFiles(String imageName) {
if(dir.isDirectory()){
for(File img : imgList){
if(img.isFile()){
MakeGrey.makeGrey(img);
}
}
}