Changing image quality

730 views Asked by At

I'm trying to create remote control application in Java. I'm using robot to capture my screen image, and then I need to send it to the server. However, because the image size may be too big for the sending to be quick as possible, I'm changing the image quality in the code.

The problem is with the code I have, after changing the image it automatically save it as file in my computer but I don't want it to. I want it to the change it without saving it to be able to send it to my server

The code:

Robot robot = null;
Rectangle rectangle = null;
GraphicsEnvironment gEnv=GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gDev=gEnv.getDefaultScreenDevice();

//Get screen dimensions
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
rectangle = new Rectangle(dim);

System.out.println(rectangle);
robot = new Robot(gDev);
BufferedImage image = robot.createScreenCapture(rectangle);


// FileInputStream inputStream = new FileInputStream(MyFile);  
// BufferedImage originalImage = ImageIO.read(inputStream);
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");  
ImageWriter writer = (ImageWriter)iter.next();  
ImageWriteParam iwp = writer.getDefaultWriteParam();  
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);  
float quality = 0.25f;  // reduce quality by 50%  
iwp.setCompressionQuality(quality);  
File file = new File("Tester6.png");

FileImageOutputStream output = new FileImageOutputStream(file);  
writer.setOutput(output);  

IIOImage image1 = new IIOImage(image, null, null);

writer.write(null, image1, iwp);  
writer.dispose();
1

There are 1 answers

0
Pace On

Instead of creating a file, do:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
writer.setOutput(ios);

You can then use baos.toByteArray() to get the bytes after you have called writer.write().