I am trying to run an image compression code in Java, and after a long time I am not using an IDE to do so, and am running the code from windows cmd itself.
Here's my code:
import java.io.*;
import java.util.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;
public class Compression {
public static void main(String[] args) throws IOException {
File input = new File("digital_image_processing.jpg");
BufferedImage image = ImageIO.read(input);
File compressedImageFile = new File("compress.jpg");
OutputStream os =new FileOutputStream(compressedImageFile);
Iterator<ImageWriter>writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.05f);
writer.write(null, new IIOImage(image, null, null), param);
os.close();
ios.close();
writer.dispose();
}
}
In cmd I am in the directory where the Compression.java is present.
This is what is happening:
Any suggestions? I have tried all the suggestions given on Stack on similar questions but none of them seem to work for me.
Assuming you showed the full code, your class is not in a package, so that's not the issue.
Your issue is likely that the current directory is not in the classpath, by default. Check it with this command:
set CLASSPATH
To run your code directly, use:
java -cp . Compression
This will run Java with the current directory as the only path in the classpath.
Related
I want to run a parralel screenshot testing, but have got an error.
I raised Xmx and Xms up, they are not eating all my RAM, which I have a 32gb.
But they fails at random point after eating it's defined memory.
Have there any solution for memory optimization ?
I comapare somewhere 18+ images which in PNG format takes nearby 200-600-800kb
This is gradle.properties.
org.gradle.parallel=false
org.gradle.caching=false
org.gradle.console=verbose
org.gradle.jvmargs=-Xmx16g -Xms4g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
systemProp.junit.jupiter.execution.parallel.enabled=true
systemProp.junit.jupiter.execution.parallel.mode.default=concurrent
systemProp.junit.jupiter.execution.parallel.mode.classes.default=concurrent
systemProp.junit.jupiter.execution.parallel.config.strategy=dynamic
systemProp.junit.jupiter.execution.parallel.config.dynamic.factor=1
My imports, there is latest versions of the libs.
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.comparison.ImageDiff;
import ru.yandex.qatools.ashot.comparison.ImageDiffer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
And some code with I find diff
protected int differenceBetweenPages(String pageName,
String actualUrl,
int scrollTime) throws IOException {
open(actualUrl);
actual = capturePage(scrollTime);
ImageIO.write(actual.getImage(), "png", actualImg(pageName));
attach = new FileInputStream(actualImg(pageName));
Allure.addAttachment("Actual page", "image/png", attach, ".png");
attach.close();
expected = expectedScreenshot(pageName);
diff = new ImageDiffer().makeDiff(expected, actual);
ImageIO.write(diff.getMarkedImage(), "png", diffImg(pageName));
attach = new FileInputStream(diffImg(pageName));
Allure.addAttachment("Diff Page", "image/png", attach, ".png");
attach.close();
return diff.getDiffSize();
}
I also had issues using Ashot library. I switched to ShutterBug instead and it's working fine.
https://github.com/assertthat/selenium-shutterbug
build.gradle snippet
compile 'com.assertthat:selenium-shutterbug:0.9.2'
API to capture the page screenshot and attach it to the Allure Report
#Attachment(value = "Page screenshot", type = "image/png")
public static byte[] captureScreenshot(WebDriver driver) {
BufferedImage screenshot = Shutterbug.shootPage(driver, ScrollStrategy.WHOLE_PAGE, true).getImage();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ImageIO.write(screenshot, "png", outputStream);
} catch (IOException e) {
e.printStackTrace();
}
return outputStream.toByteArray();
}
Hi I want to compress and store compressed image to folder. So I have used the below code,
import java.io.*;
import java.util.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;
public class Compression {
public static void main(String[] args) throws IOException {
String dc = "C:\\Users\\admin\\Desktop\\RFI\\DC\\1_1_c.jpg";
String dr = "C:\\Users\\admin\\Desktop\\RFI\\DR";
File file = new File(dc);
BufferedImage image = ImageIO.read(file);
OutputStream os =new FileOutputStream(new File(dr));
Iterator<ImageWriter>writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.05f);
writer.write(null, new IIOImage(image, null, null), param);
os.close();
ios.close();
writer.dispose();
}
}
But i'm not get compressed image. Only get the below error on console
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at com.opencv.Compression.main(Compression.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Please suggest me any idea....
This would deserve a comment more than an answer but since my reputation is so low, I can't comment and am forced to write it as an answer.
Did you try to understand the error you get ? The call stack is pretty clear. You have an error at the line BufferedImage image = ImageIO.read(file);. The program can't find your image. Did you make sure that the image file specified in String dc = "C:\\Users\\admin\\Desktop\\RFI\\DC\\1_1_c.jpg"; actually existed ?
I have images of codes that I want to decode. How can I use zxing so that I specify the image location and get the decoded text back, and in case the decoding fails (it will for some images, that's the project), it gives me an error.
How can I setup zxing on my Windows machine? I downloaded the jar file, but I don't know where to start. I understand I'll have to create a code to read the image and supply it to the library reader method, but a guide how to do that would be very helpful.
I was able to do it. Downloaded the source and added the following code. Bit rustic, but gets the work done.
import com.google.zxing.NotFoundException;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Reader;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.Result;
import com.google.zxing.LuminanceSource;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.*;
import com.google.zxing.qrcode.QRCodeReader;
class qr
{
public static void main(String args[])
{
Reader xReader = new QRCodeReader();
BufferedImage dest = null;
try
{
dest = ImageIO.read(new File(args[0]));
}
catch(IOException e)
{
System.out.println("Cannot load input image");
}
LuminanceSource source = new BufferedImageLuminanceSource(dest);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Vector<BarcodeFormat> barcodeFormats = new Vector<BarcodeFormat>();
barcodeFormats.add(BarcodeFormat.QR_CODE);
HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>(3);
decodeHints.put(DecodeHintType.POSSIBLE_FORMATS, barcodeFormats);
decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
Result result = null;
try
{
result = xReader.decode(bitmap, decodeHints);
System.out.println("Code Decoded");
String text = result.getText();
System.out.println(text);
}
catch(NotFoundException e)
{
System.out.println("Decoding Failed");
}
catch(ChecksumException e)
{
System.out.println("Checksum error");
}
catch(FormatException e)
{
System.out.println("Wrong format");
}
}
}
The project includes a class called CommandLineRunner which you can simply call from the command line. You can also look at its source to see how it works and reuse it.
There is nothing to install or set up. It's a library. Typically you don't download the jar but declare it as a dependency in your Maven-based project.
If you just want to send an image to decode, use http://zxing.org/w/decode.jspx
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.
So I am trying to write an .sh file that will be executable, this is how I'm currently writing it:
Writer output = null;
try {
output = new BufferedWriter(new FileWriter(file2));
output.write(shellScriptContent);
output.close();
} catch (IOException ex) {
Logger.getLogger(PunchGUI.class.getName()).log(Level.SEVERE, null, ex);
}
So that writes the file just fine, but it is not executable. Is there a way to change the executable status when I write it?
Edit: To further clarify, I am trying to make it execute by default, so that for instance, if you double clicked the generated file, it would automatically execute.
You can call File.setExecutable() to set the owner's executable bit for the file, which might be sufficient for your case. Or you can just chmod it yourself with a system call with Process.
Alas, full-powered programmatic alteration of file permissions isn't available until Java 7. It'll be part of the New IO feature set, which you can read more about here.
You'd need to chmod it, and you can probably do it by exec'ing a system command like such:
Really all you'd need is to fire off something like this:
Runtime.getRuntime().exec("chmod u+x "+FILENAME);
But if you want to keep track of it more explicitly can capture stdin / stderr then something more like:
Process p = Runtime.getRuntime().exec("chmod u+x "+FILENAME);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
Which I got from here:
http://www.devdaily.com/java/edu/pj/pj010016/pj010016.shtml
Update:
Test program:
package junk;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Main{
private String scriptContent = '#!/bin/bash \n echo "yeah toast!" > /tmp/toast.txt';
public void doIt(){
try{
Writer output = new BufferedWriter(new FileWriter("/tmp/toast.sh"));
output.write(scriptContent);
output.close();
Runtime.getRuntime().exec("chmod u+x /tmp/toast.sh");
}catch (IOException ex){}
}
public static void main(String[] args){
Main m = new Main();
m.doIt();
}
}
On linux if you open up a file browser and double click on /tmp/toast.sh and choose to run it, it should generate a text file /tmp/toast.txt with the words 'yeah toast'. I assume Mac would do the same since it's BSD under the hood.
In Java 7 you can call Files.setPosixFilePermissions. Here is an example:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Set;
class FilePermissionExample {
public static void main(String[] args) throws IOException {
final Path filepath = Paths.get("path", "to", "file.txt");
final Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(filepath);
permissions.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(filepath, permissions);
}
}
On Mac OS X, besides chmod +x, you have to give a .command extension to your shell script if you want to launch it with a double-click.
This answer I wrote for the question how do I programmatically change file permissions shows a chmod example via a native call using jna, which should work on Mac OS X.