I am trying to resize the picture with file chooser. It seems everything is file, but I can't open it after adding in folder.
public void metodAddpath(String fullPath) {
try {
File sourceFile = new File(fullPath);
BufferedImage bufferedimage = ImageIO.read(sourceFile);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedimage, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
FileOutputStream fileOutputStream = new FileOutputStream(
sourceFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = is.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
is.close();
fileOutputStream.close();
//scaleImage(bufferedimage, 220, 220);
} catch(Exception e) {
e.printStackTrace();
}
}
After I push the button to save the image in folder.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Database base = new Database();
metodAddpath(jTextField1.getText());
base.addPictureResource(jTextField1.getText());
}
But when I am trying to add it in folder, there is a mistake.
I'm just going to come out and say it, none of this...
try {
File sourceFile = new File(fullPath);
BufferedImage bufferedimage = ImageIO.read(sourceFile);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedimage, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
FileOutputStream fileOutputStream = new FileOutputStream(
sourceFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = is.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
is.close();
fileOutputStream.close();
//scaleImage(bufferedimage, 220, 220);
} catch(Exception e) {
e.printStackTrace();
}
makes sense.
You're reading the image, writing it to a ByteArrayOutputStream, piping that through a InputStream which you're then using to write the contents to another file via a FileOutputStream ... why?!
Something like...
File sourceFile = new File(fullPath);
try {
BufferedImage bufferedimage = ImageIO.read(sourceFile);
//scaleImage(bufferedimage, 220, 220);
// Beware, this is overwriting the existing file
try (FileOutputStream fileOutputStream = new FileOutputStream(sourceFile)) {
ImageIO.write(bufferedimage, "jpg", fileOutputStream);
}
} catch(Exception e) {
e.printStackTrace();
}
would do the same job, is easier to read and probably more efficient...
I doubt this will answer you question, but it might reduce some of the confusion
Finally, I found the way how to scale the image before saving in the folder. First I would like to add a listener for the button and get the image with file chooser.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpeg", "jpg", "png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if(result ==JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
//GET ABSOLUTE PATH OF PICTURES
jTextField1.setText(selectedFile.getAbsolutePath());
//addPicture.setText(selectedFile.getName());
//GET NAME OF PICTURES
//getPicName = selectedFile.getName();
} else if(result == JFileChooser.CANCEL_OPTION) {
System.out.println("File not found!");
}
}
After I am adding a listener for another button that is responsible for adding a picture to the folder. Here is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
addPicture(jTextField1.getText());
}catch(Exception e) {
e.printStackTrace();
}
}
And finally, let's add two functions:
public void addPicture(String fullPath) throws IOException {
File sourceFile = new File(fullPath);
try {
BufferedImage bufferedimage = ImageIO.read(sourceFile);
// add method scaleImage(bufferedimage, 220, 220) in ImageIO.write(scaleImage(bufferedimage, 220, 220), "jpg", fileOutputStream)
try (FileOutputStream fileOutputStream = new FileOutputStream("/my files/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/" + sourceFile.getName())) {
ImageIO.write(scaleImage(bufferedimage, 220, 220), "jpg", fileOutputStream);
}
} catch(Exception e) {
e.printStackTrace();
}
Add don't forget about the important method
public BufferedImage scaleImage(BufferedImage img, int width, int height) {
int imgWidth = img.getWidth();
int imgHeight = img.getHeight();
if (imgWidth*height < imgHeight*width) {
width = imgWidth*height/imgHeight;
} else {
height = imgHeight*width/imgWidth;
}
BufferedImage newImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = newImage.createGraphics();
try {
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.clearRect(0, 0, width, height);
g.drawImage(img, 0, 0, width, height, null);
}
finally {
g.dispose();
}
return newImage;
}
}
Thanks averyone for help. I would like to say thanks to MadProgrammer. You're a genius, man.
Related
I'm creating a simple stream to send images taken from client's screen from client to server. For now I can receive the first image but then the app crashed unexpectedly. The idea is send the size and the image in byte array, the server receive that byte array and convert to image.
FromClient:
public void run() {
image = new BufferedImage(NORM_PRIORITY, MIN_PRIORITY, MAX_PRIORITY);
while(continueLoop) {
//send captured screen
image = robot.createScreenCapture(rectangle);
try {
//Initiate the stream
OutputStream out = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
// store the size of each image
byte[] size = ByteBuffer.allocate(4).putInt(baos.size()).array();
dos.write(size);
dos.write(baos.toByteArray(), 0, baos.toByteArray().length);
dos.flush();
} catch(IOException e) {
e.printStackTrace();
e.printStackTrace();
continueLoop = false;
}
try {
Thread.sleep(30);
} catch(InterruptedException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
ToServer:
public void run() {
boolean continueLoop = true;
try {
drawGUI();
// Initiate the stream
InputStream is = clientSocket.getInputStream();
DataInputStream configGraphicStream = new DataInputStream(is);
BufferedImage image = null;
while(continueLoop) {
//receive the size of image and convert to type int
byte[] sizeInByte = new byte[64];
configGraphicStream.read(sizeInByte);
int length = ByteBuffer.wrap(sizeInByte).asIntBuffer().get();
try {
// Get images
byte[] img = new byte[length];
configGraphicStream.readFully(img, 0, img.length);
image = ImageIO.read(new ByteArrayInputStream(img));
}
catch (Exception e) {
System.out.println(e.getMessage());
}
//draw images
if( image != null)
{
Graphics graphics = clientPanel.getGraphics();
graphics.drawImage(image, 0, 0, clientPanel.getWidth(), clientPanel.getHeight(), clientPanel);
}
System.out.println("Receiving image");
Thread.sleep(30);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Please help me solve this problem.
There was a problem with saving the graphics I received in the form of a picture in a folder on the computer. It seems to me that the problem is in the saving method in the picture, but I do not know how to fix the problem. I marked the problem area in the code (saveImage), I hope for your help)
//create Graph
XYSeriesCollection seriesCollection1 = new XYSeriesCollection(series1);
chart1 = ChartFactory.createXYLineChart("Зависимость скорости полета от t",
"Время, с", "Скорость полета, км/ч", seriesCollection1, PlotOrientation.VERTICAL, false, true, false);
chartPanel1 = new ChartPanel(chart1);
chartPanel1.setPreferredSize(new Dimension(1300, 480));
panel.add(chartPanel1);
//saving method in picture
public void saveImage(File file) {
Rectangle rec = chartPanel1.getBounds();
BufferedImage img = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
print(img.getGraphics()); // I think problem here.
try {
ImageIO.write(img, "png", file);
JOptionPane.showMessageDialog(null, "Данное изображение сохранено", "", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Ошибка сохранения", "", JOptionPane.ERROR_MESSAGE);
}
}
//listener
saveImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == saveImage) {
JFileChooser fc = new JFileChooser();
int op = fc.showSaveDialog(OpenFIle.this);
if (op == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if (len > 4){
ext = filename.substring(len - 4, len);
}
if (ext.equals(".png")){
file = path + "\\" + filename;
}else {
file = path + "\\" + filename + ".png";
}
saveImage(new File(file));
}
}
}
});
}
The problem was solved in this way
public void saveImage(File file) {
Rectangle rec = chartPanel1.getBounds();
BufferedImage img = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
chartPanel1.paint(g);
try {
ImageIO.write(img, "png", file);
JOptionPane.showMessageDialog(null, "Данное изображение сохранено", "", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
}
}
I am trying to create import images and mp3 files from one directory using a file chooser and save them to another . The images went fine but I cant seem to find out how to save the mp3 file .
Images
#Override
public void saveFile(File file) {
//Get image path
String imagePath = file.getAbsolutePath();
String imageName = file.getName();
System.out.println(imagePath);
//Read image
try {
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bufferedImage = ImageIO.read(new File(imagePath));
System.out.println("Reading complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
//write image
try {
f = new File("H:\\TestFolder\\images\\" + imageName); //output file path
ImageIO.write(bufferedImage, "jpg", f);
System.out.println("Writing complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
Mp3
#Override
public void saveFile(File file) {
try{
f = new File(file, "H:\\TestFolder\\test.mp3"); //file.getAbsolutePath();
}catch (Exception e) {
e.printStackTrace();
}
}
Use Files.copy(source, target, REPLACE_EXISTING);
https://docs.oracle.com/javase/tutorial/essential/io/copy.html
Try it like this:
File f = new File("H:\\TestFolder\\test.mp3");
InputStream is = new FileInputStream(f);
OutputStream outstream = new FileOutputStream(new File("H:\\TestFolder2\\blabla.mp3"));
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
outstream.close();
I'm currently working on a remote desktop app. The server part runs on Android device and the client one on PC/Raspberry PI. I've encountered a problem with receiving my bitmaps (screenshots from Android, send as byte arrays).
The Android Server code goes like this:
//os = new ObjectOutputStream(s.getOutputStream());
public void run() {
while(true){
try {
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
int quality = 100;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
byte[] byteArray = stream.toByteArray();
if(byteArray.length>0) {
os.writeInt(byteArray.length);
os.write(byteArray, 0, byteArray.length);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
}}}
And the Receiver App on PC like this:
//ois = new ObjectInputStream(s.getInputStream());
public void run() {
while(true){
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int size = ois.readInt();
System.out.println(size);
byte[] data = new byte[size];
int length = 0;
while ((length = ois.read(data,0,size)) != -1) {
out.write(data, 0, size);
out.flush();
}
byte[] bytePicture = out.toByteArray();
out.close();
BufferedImage buffImage = byteArrayToImage(bytePicture);
ImageIcon imgIcon = new ImageIcon(buffImage);
l.setIcon(imgIcon);
} catch (IOException e) {
}}}
byteArrayToImage
public static BufferedImage byteArrayToImage(byte[] bytes) {
BufferedImage bufferedImage = null;
try {
InputStream inputStream = new ByteArrayInputStream(bytes);
bufferedImage = ImageIO.read(inputStream);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return bufferedImage;
}
The problem is that in the receiver app I get Java OutOfMemoryException because I cannot differ between incoming screenshots. I really cannot figure out how to read exactly the size of a bitmap (as byte array) then display it and read another and another one. Any help will be appreciated. Thanks in advance.
The JPEG Images that ImageIO generated view correctly on windows file explorer, as well as safari webbrowser, but in FireFox, the resampled images are clipped.
How do I use ImageIO without corrupting the resamples?
The code should resize image keeping aspect ratio, as well as do jpeg compression, the convert it to a byte [] array, which could be written to a socket.
some of my code. in this snippet, I tried adding Jui library, but still the same issue.
public static BufferedImage imageistream;
public void Resample(String child,double width,double height) throws Exception, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException, MissingParameterException, WrongParameterException
{
String imagePath = "";
if(this.is_mac_unix == true)
{
imagePath = this.path+"/"+child;
}
else
{
imagePath = this.path+"\\"+child;
}
PixelImage bmp = null;
try {
bmp = ToolkitLoader.loadViaToolkitOrCodecs(imagePath, true, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Resample resample = new Resample();
resample.setInputImage(bmp);
double fixedRatio = width/height;
if(((double)bmp.getWidth()/bmp.getHeight()) >= fixedRatio)
{
resample.setSize((int)width,(int)(bmp.getHeight()/(bmp.getWidth()/width)));
}
else
{
resample.setSize((int)width,(int)(bmp.getWidth()/(bmp.getHeight()/height)));
}
resample.setFilter(Resample.FILTER_TYPE_LANCZOS3);
resample.process();
PixelImage scaledImage = resample.getOutputImage();
Processor.imageistream = ImageCreator.convertToAwtBufferedImage(scaledImage);
bmp = null;
Runtime rt = Runtime.getRuntime();
rt.gc();
}
...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(Processor.imageistream, "jpg", baos);
// ImageIO.write(Processor.imageistream, "png", baos); Works!
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte bytes[] = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
OutputStream os = (OutputStream)obj[1];
OutputStreamWriter writer = (OutputStreamWriter)obj[0];
byte[] buf= new byte[4096];
int c;
try {
while (true) {
c= is.read(buf);
if (c<= 0) break;
os.write(buf, 0, c);
}
writer.close();
os.close();
is.close();
I've been successfully using:
BufferedImage bufferedImage = ImageIO.read(..);
Image img = bufferedImage.getScaledInstance(..);
BufferedImage result = // transform Image to BufferedImage
ImageIO.write(result, "image/jpeg", response.getOutputStream());
transformation is simply writing the contents of the image to a new BufferedImage