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();
}
}
Related
I need to make notification on screen after pdf file had dowloaded. File dowload? but I cannot do notification on screen.
public void createDocumentAboutRegistration(User user){
PdfDocument myPdfDocument = new PdfDocument();
PdfDocument.PageInfo myPageInfo = new PdfDocument.PageInfo.Builder(300,600,1).create();
PdfDocument.Page myPage = myPdfDocument.startPage(myPageInfo);
Paint myPaint = new Paint();
String myString = user.toString();
int x = 10, y=25;
for (String line:myString.split("\n")){
myPage.getCanvas().drawText(line, x, y, myPaint);
y+=myPaint.descent()-myPaint.ascent();
}
myPdfDocument.finishPage(myPage);
String myFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
String nameFile = "coupon-" + user.lastName + ".pdf";
File myFile = new File(myFilePath, nameFile);
try {
myPdfDocument.writeTo(new FileOutputStream(myFile));
Toast.makeText(RegistrationActivity.this, "Coupon generated and saved in your downloads.", Toast.LENGTH_LONG).show();
}
catch (Exception e){
e.printStackTrace();
Toast.makeText(RegistrationActivity.this, "Error", Toast.LENGTH_LONG).show();
}
myPdfDocument.close();
}
I am unable to print pdf with MONOCHROME option on MAC, even
monochrome option is selected but still on MAC its printing in
COLOR but on windows its working fine for both options MONOCHROME and COLOR.
Plus, On MAC settings are disable even proper printer is connected.
but the same code running on windows its working fine in every
scenario.
I am using macOS High Sierra version 10.13.6
public boolean printFile(String fileUrl) {
PrintService[] printServicesAll = PrintServiceLookup.lookupPrintServices(null, null);
PrintService[] printServicesFiltered;
PrintRequestAttributeSet attrib = new HashPrintRequestAttributeSet();
Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds();
String OS = System.getProperty("os.name").toLowerCase();
attrib.add(new Copies(1));
attrib.add(new sun.print.DialogOnTop());
attrib.add(Chromaticity.MONOCHROME);
attrib.add(DialogTypeSelection.NATIVE);
PrintService selectedPrintService = null;
if (OS.contains("win")) {
if (printServicesAll.length > 0) {
printServicesFiltered = removeLogicalPrinters(printServicesAll);
selectedPrintService = ServiceUI.printDialog(null, screen.width / 3, screen.height / 3, printServicesFiltered, printServicesFiltered[0], null, attrib);
}
} else if (OS.contains("mac")) {
if (printServicesAll.length > 0) {
selectedPrintService = ServiceUI.printDialog(null, screen.width / 3, screen.height / 3, printServicesAll, printServicesAll[0], null, attrib);
}
}
if (attrib.get(Destination.class) != null) {
JOptionPane.showMessageDialog(null, "Print to file option not allowed!");
return false;
} else {
if (selectedPrintService != null)
System.out.println("selected printer: " + selectedPrintService.getName());
else
return false;
try {
DocPrintJob job = selectedPrintService.createPrintJob();
job.addPrintJobListener(new PrintJobAdapter() {
public void printDataTransferCompleted(PrintJobEvent event) {
System.out.println("data transfer complete");
}
public void printJobNoMoreEvents(PrintJobEvent event) {
System.out.println("received no more events");
}
});
print(selectedPrintService, fileUrl, attrib);
/*File file = new File(filePath);
Desktop.getDesktop().print(file);*/
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Main Print File Method
private boolean print(PrintService printService, String fileUrl, PrintRequestAttributeSet attributes)
throws PrintException {
try {
PDDocument pdf = null;
String fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
if (fileType.equalsIgnoreCase("bmp") || fileType.equalsIgnoreCase("gif") || fileType.equalsIgnoreCase("jpg") || fileType.equalsIgnoreCase("png")) {
try {
InputStream in = new URL(fileUrl).openStream();
PDDocument document = new PDDocument();
BufferedImage bImg = ImageIO.read(in);
float width = bImg.getWidth();
float height = bImg.getHeight();
PDPage page = new PDPage(new PDRectangle(width, height));
document.addPage(page);
PDImageXObject img = LosslessFactory.createFromImage(document, bImg);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 0, 0);
contentStream.close();
in.close();
pdf = document;
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPageable(new PDFPageable(pdf));
job.print(attributes);
pdf.close();
} catch (Exception e) {
e.printStackTrace();
}
} else if (fileType.equalsIgnoreCase("txt")) {
JEditorPane jEditorPane = new JEditorPane(fileUrl);
jEditorPane.print(null, null, false, printService, null, false);
} else if (fileType.equalsIgnoreCase("pdf")) {
pdf = PDDocument.load(new URL(fileUrl).openStream());
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPageable(new PDFPageable(pdf));
job.print(attributes);
pdf.close();
}
} catch (Exception e) {
throw new PrintException("Printer exception", e);
}
return true;
}
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.
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've created an app with utilities I usually use on my pc (like sending shutdown to cmd.exe) and as some friends asked me to give it to them I was trying to add an update system that checks for updates on a server to make it easier that their version is always updated.
The thing is that I've been over the net searching any solution but all of them just tell to use .close() and my file has it right after stop needing it. When I run it everything works fine and there are no exceptions thrown, so I just dunno what can be wrong.
Whole class:
public class Main_Gui extends JFrame {
private Thread worker;
private final String root = "update/";
private JTextArea outText;
private JButton cancel;
private JButton launch;
private JScrollPane sp;
private JPanel pan1;
private JPanel pan2;
private String zipFile = "Actualización.zip";
private String path = "http://ritsu.hol.es/url.html";
private String TITLE = "RitsUtilities | Actualizador";
public Main_Gui() {
initComponents();
outText.setText("Conectando con el servidor...");
download();
}
private void initComponents() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setTitle(TITLE);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pan1 = new JPanel();
pan1.setLayout(new BorderLayout());
pan2 = new JPanel();
pan2.setLayout(new FlowLayout());
outText = new JTextArea();
sp = new JScrollPane();
sp.setViewportView(outText);
launch = new JButton("Ejecutar RitsUtilities");
launch.setEnabled(false);
launch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] run = { "java", "-jar", "RitsUtilities.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
launch();
}
});
pan2.add(launch);
cancel = new JButton("Salir");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pan2.add(cancel);
pan1.add(sp, BorderLayout.CENTER);
pan1.add(pan2, BorderLayout.SOUTH);
add(pan1);
pack();
setSize(500, 400);
setLocationRelativeTo(null);
}
private void download() {
worker = new Thread(new Runnable() {
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
});
worker.start();
}
private void launch() {
String[] run = { "java", "-jar", "update app.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
}
private void cleanup() {
outText.setText(outText.getText() + "\nLimpiando archivos temporales...");
remove(new File(root));
new File(root).delete();
}
private void remove(File f) {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
remove(ff);
ff.delete();
} else {
ff.delete();
}
}
}
private void copyFiles(File f, String dir) throws IOException {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
new File(dir + "/" + ff.getName()).mkdir();
copyFiles(ff, dir + "/" + ff.getName());
} else {
copy(ff.getAbsolutePath(), dir + "/" + ff.getName());
}
}
}
public void copy(String srFile, String dtFile) throws FileNotFoundException, IOException {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private void unzip() throws IOException {
int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(zipFile);
Enumeration e = zipfile.entries();
(new File(root)).mkdir();
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
outText.setText(outText.getText() + "\nExtrayendo: " + entry);
if (entry.isDirectory())
(new File(root + entry.getName())).mkdir();
else {
(new File(root + entry.getName())).createNewFile();
is = new BufferedInputStream(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(root + entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
}
}
private void downloadFile(String link) throws MalformedURLException, IOException {
URL url = new URL(link);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
long max = conn.getContentLength();
outText.setText(outText.getText() + "\n" + "Descargando archivo...\nTamaño de la actualización(comprimida): " + max + " Bytes");
BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(zipFile)));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
int in = 0;
while ((bytesRead = is.read(buffer)) != -1) {
in += bytesRead;
fOut.write(buffer, 0, bytesRead);
}
fOut.flush();
fOut.close();
is.close();
outText.setText(outText.getText() + "\n¡Descarga completada!");
}
private String getDownloadLinkFromHost() throws MalformedURLException, IOException {
URL url = new URL(path);
InputStream html = null;
html = url.openStream();
int c = 0;
StringBuilder buffer = new StringBuilder("");
while (c != -1) {
c = html.read();
buffer.append((char) c);
}
return buffer.substring(buffer.indexOf("[url]") + 5, buffer.indexOf("[/url]"));
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main_Gui().setVisible(true);
}
});
}
}
EDIT: changed private String zipFile = "Actualización.zip"; to private String zipFile = "Update.zip"; but still just deleting temp files/directories but not that "Update.zip" folder that the app downloads.
The File#delete() method you are using doesn't throw an error if the file can't be deleted, it returns false. This is documented in the Javadoc, together with an alternative solution (emphasize mine):
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
Finally it's working, just added a forced delete on run() inside download() so now my code looks like
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
+ System.gc();
+ File tmpf = new File(zipFile);
+ tmpf.deleteOnExit();
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
I'm pretty sure that there are way better ways to do this, but that one seems to work for me.
Thanks to everyone that answered and tried to help me. =D
I would suggest improving your remove(File f) method. Add some checks for the Boolean return value of ff.delete(), that will tell you if the file is actually being deleted or not.
Also, you could add some logs into that method, so you could debug what is actually doing, perhaps it's not seeing the files or something.
One last comment. You should make your code more modular. Create more abstractions and give each of them a simple task. That is the essence of Object Oriented Design. Then, you can program some JUnit tests for each object, and you can run the tests every time you make a change. I reccomend you give a look to this article on Cohesion