I tried the code for saving png files found here and it works.
But I want to save a vector image, so I changed the terminal to: PostscriptTerminal and SVGTerminal. For the SVGTerminal the output in empty and when I use the PostscriptTerminal the code hangs at p.plot();
ImageTerminal png = new ImageTerminal();
PostscriptTerminal eps = new PostscriptTerminal();
SVGTerminal svg = new SVGTerminal();
File file = new File("D:/plot.eps");
try {
file.createNewFile();
eps.processOutput(new FileInputStream(file));
} catch (FileNotFoundException ex) {
System.err.print(ex);
} catch (IOException ex) {
System.err.print(ex);
}
PlotStyle myPlotStyle = new PlotStyle();
myPlotStyle.setStyle(Style.POINTS);
myPlotStyle.setPointType(7); // 7 - circle
myPlotStyle.setLineType(3); // blue color
JavaPlot p = new JavaPlot();
p.setPersist(false);
p.setTerminal(eps);
//p.setTitle(algorithm_name+" - "+problem_name, "Arial", 20);
p.getAxis("x").setLabel("X axis", "Arial", 15);
p.getAxis("y").setLabel("Y axis","Arial", 15);
p.setKey(JavaPlot.Key.TOP_RIGHT);
double[][] front = this.writeObjectivesToMatrix();
DataSetPlot s = new DataSetPlot(front);
s.setPlotStyle(myPlotStyle);
s.setTitle("");
p.addPlot(s);
p.plot(); //code hangs here if I use PostscriptTerminal
try {
//ImageIO.write(png.getImage(), "png", file); //works
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write (eps.getTextOutput());
//Close writer
writer.close();
} catch (IOException ex) {
System.err.print(ex);
}
I managed to save an .eps file. I only needed to add a file path in constructor and it worked.
PostscriptTerminal eps = new PostscriptTerminal("output.eps");
PlotStyle myPlotStyle = new PlotStyle();
myPlotStyle.setStyle(Style.POINTS);
myPlotStyle.setPointType(7); // 7 - circle
myPlotStyle.setLineType(3); // blue color
JavaPlot p = new JavaPlot();
p.setPersist(false);
p.setTerminal(eps);
p.getAxis("x").setLabel("X axis", "Arial", 15);
p.getAxis("y").setLabel("Y axis","Arial", 15);
p.setKey(JavaPlot.Key.TOP_RIGHT);
double[][] front = this.writeObjectivesToMatrix();
DataSetPlot s = new DataSetPlot(front);
s.setPlotStyle(myPlotStyle);
s.setTitle("");
p.addPlot(s);
p.plot();
Related
I want to take a screenshot of my screen while in Google Chrome but when my screenshot saves its only my desktop? Im on a mac btw
try {
Robot robot = new Robot();
String format = "jpg";
String fileName = "FullScreenshot." + format;
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, format, new File(fileName));
System.out.println("A full screenshot saved!");
} catch (AWTException | IOException ex) {
System.err.println(ex);
}
I am having html content store as a raw string in my database and I like to print it in pdf, but with custom size, for example page size to be 10cm width and 7 com height, not standard A4 format.
Can someone gives me some examples if it is possible.
ByteArrayOutputStream out = new ByteArrayOutputStream();
PDRectangle rec = new PDRectangle(recWidth, recHeight);
PDPage page = new PDPage(rec);
try (PDDocument document = new PDDocument()) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.defaultTextDirection(BaseRendererBuilder.TextDirection.LTR);
String htmlContent = "<b>Hello world</b>" + content;
builder.withHtmlContent(htmlContent, "");
document.addPage(page);
builder.usePDDocument(document);
PdfBoxRenderer renderer = builder.buildPdfRenderer();
renderer.createPDFWithoutClosing();
document.save(out);
} catch (Exception e) {
ex.printStackTrace();
}
return new ByteArrayInputStream(out.toByteArray());
This code generates for me 2 files, one small and one A4.
UPDATE:
I tried this one:
try (PDDocument document = new PDDocument()) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.defaultTextDirection(BaseRendererBuilder.TextDirection.LTR);
builder.useDefaultPageSize(210, 297, PdfRendererBuilder.PageSizeUnits.MM);
builder.usePdfAConformance(PdfRendererBuilder.PdfAConformance.PDFA_3_A);
String htmlContent = "<b>content</b>";
builder.withHtmlContent(htmlContent, "");
builder.usePDDocument(document);
PdfBoxRenderer renderer = builder.buildPdfRenderer();
renderer.createPDFWithoutClosing();
document.save(out);
} catch (Exception e) {
log.error(">>> The creation of PDF is invalid!");
}
But in this case content is not shown, if I remove useDefaultPageSize, content will be shown
I didn't check this solution before, but try initialise the builder object with your desired page size and document type like below
builder.useDefaultPageSize(210, 297, PdfRendererBuilder.PageSizeUnits.MM);
builder.usePdfAConformance(PdfRendererBuilder.PdfAConformance.PDFA_3_A);
the lib include many PDF format next is PdfAConformance Enum with possible values
PdfAConformance Enum
I am adding text to an image using this code in Android :
public Bitmap drawTextToBitmap(Context gContext, Bitmap image, String gText) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
android.graphics.Bitmap.Config bitmapConfig =
image.getConfig();
// set default bitmap config if none
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
// resource bitmaps are imutable,
// so we need to convert it to mutable one
Bitmap bitmap = null;
try{
bitmap = image.copy(bitmapConfig, true);
image.recycle();
Canvas canvas = new Canvas(bitmap);
// new antialised Paint
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// text color - #3D3D3D
paint.setColor(Color.WHITE);
// text size in pixels
paint.setTextSize((int) (50 * scale));
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.BLACK);
// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
int padding = bounds.height()/2;
int x = bitmap.getWidth() - (bounds.width()+padding);
int y = (bitmap.getHeight() - (bounds.height()+padding));
canvas.drawText(gText, x, y, paint);
}catch (Throwable e){
AppLog.e("DrawingBitmap","error while adding timestamp",e);
}
return bitmap;
}
Then I create a new File with the transformed bitmap
storeImage(newBitmap, newFileName);
private File storeImage(Bitmap image, String nameFile) {
File pictureFile = new File(getExternalCacheDir(), nameFile);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (FileNotFoundException e) {
AppLog.e("error creating bitmap", "File not found: " + e.getMessage());
} catch (IOException e) {
AppLog.e("error creating bitmap", "Error accessing file: " + e.getMessage());
}
return pictureFile;
}
I send the file to my server, I receive an input stream, I create a File, I scale it and I create a new File with the scaled image :
ImageWriter.write(metadata, new IIOImage(image, null, metadata), param);
I get an IIOException:
javax.imageio.IIOException: Missing Huffman code table entry
at com.sun.imageio.plugins.jpeg.JPEGImageWriter.writeImage(Native Method)
at com.sun.imageio.plugins.jpeg.JPEGImageWriter.writeOnThread(JPEGImageWriter.java:1067)
at com.sun.imageio.plugins.jpeg.JPEGImageWriter.write(JPEGImageWriter.java:363)
at com.twelvemonkeys.imageio.plugins.jpeg.JPEGImageWriter.write(JPEGImageWriter.java:162)
if I don't call drawTextToBitmap() from android I don't get that error.
If someone can help me ... thx
EDIT : here is the way I use to get metadata from my file
private static IIOMetadata readMetaData(File source) {
try {
ImageInputStream stream = ImageIO.createImageInputStream(source);
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
IIOMetadata metadata = null;
if (readers.hasNext()) {
ImageReader reader = readers.next();
reader.setInput(stream);
metadata = reader.getImageMetadata(0);
}
return metadata;
}catch (Exception e){
_logger.error(e);
e.printStackTrace();
}
return null;
}
Edit 2 :
Using jpegParams.setOptimizeHuffmanTables(true); works but it resets all metadata and I want to keep them like gps location ...
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
if (param instanceof JPEGImageWriteParam) {
((JPEGImageWriteParam) param).setOptimizeHuffmanTables(true);
}
IIOImage image = new IIOImage(reader.read(0), null, reader.getImageMetadata(0));
writer.write(null, image, param);
here's my code, which keeps the metadata of image, and get rid of "missing huffman code table" stuff.
I state that I use NetBeans 8.2. I need to transfer a jframe (which represents an invoice) on a paragraph of IText. Everything works and is displayed. However, I get that the writings and details of the pdf I created are not well defined and displayed.
For example, the strings seem to have a shaded effect so that instead of being only black, they have gray shades. It is particularly annoying when I print: the smaller text is not readable. The same effect does not occur in the video display.
I tried modifying the jframe size and scaling the graphic2d instance. Then I returned to normal size and I modified the scale of the paragraph and so I got a result a bit 'better but not satisfactory.
Any suggestions?
Edit: this is the code of the method that manages the creation of the paragraph:
private Paragraph creaParPdf(float scaleFactorW, float scaleFactorH) throws BadElementException, IOException {
BufferedImage img = new BufferedImage(fatt.getWidth(), fatt.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D img2D = img.createGraphics();
img2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
fatt.paint(img2D);
Paragraph p = new Paragraph();
com.itextpdf.text.Image itextImg =
com.itextpdf.text.Image.getInstance(img, Color.white, false);
itextImg.scaleAbsolute(PageSize.A4.getWidth()*scaleFactorW, PageSize.A4.getHeight()*scaleFactorH);
p.add(itextImg);
return p;
}
And this is the code of the method that manages the creation of the pdf:
public void printPDF() throws FileNotFoundException, DocumentException, SQLException, ClassNotFoundException, IOException{
fatt = this;
Document d = new Document(PageSize.A4,10,10,10,10);
d.setMargins(10, 10, 0, 10);
String salvPath = "C:\\"+cliente+".pdf";
filePDF = new File(salvPath);
filePDF.getParentFile().mkdirs();
if (filePDF.exists())
out.println("Il file " + salvPath + " esiste");
else try {
if (filePDF.createNewFile())
out.println("Il file " + salvPath + " è stato creato");
else
out.println("Il file " + salvPath + " non può essere creato");
} catch (IOException ex) {
getLogger(JFrameStart.class.getName()).log(SEVERE, null, ex);
}
FileOutputStream fs = new FileOutputStream (salvPath);
PdfWriter writer = PdfWriter.getInstance(d, fs);
writer.setFullCompression();
d.open ();
try {
float scaleFactorW = 0.98f;
float scaleFactorH = 0.98f;
float offset = 0.0f;
p = creaParPdf(scaleFactorW,scaleFactorH);
} catch (BadElementException ex) {
Logger.getLogger(JFrameTracc.class.getName()).log(Level.SEVERE, null, ex);
}
d.add(p);
d.close();
}
This is the final result, by printing the pdf you can see how the smaller parts are practically illegible:
enter image description here
I want to save the image on disk such as c:/images which is captured by webcam using java ..and again I want to display that image on JForm as a label...
is this possible using java and netbeans
I'm new in java
you can save image
private static void save(String fileName, String ext) {
File file = new File(fileName + "." + ext);
BufferedImage image = toBufferedImage(file);
try {
ImageIO.write(image, ext, file); // ignore returned boolean
} catch(IOException e) {
System.out.println("Write error for " + file.getPath() +
": " + e.getMessage());
}
}
and read image from disk and show into label as
File file = new File("image.gif");
image = ImageIO.read(file);
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
You can use BufferedImage to load an image from your hard disk :
BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}
Try this link for further information. Reading/Loading Images in Java
And this one for saving the image. Writing/Saving an Image
try {
// retrieve image
BufferedImage bi = getMyImage();
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
...
}
Pure Java, not third party library needed:
byte[] image = /*your image*/
String filePath = /*destination file path*/
File file = new File(filePath);
try (FileOutputStream fosFor = new FileOutputStream(file)) {
fosFor.write(image);
}
//Start Photo Upload with No//
if (simpleLoanDto.getPic() != null && simpleLoanDto.getAdharNo() != null) {
String ServerDirPath = globalVeriables.getAPath() + "\\";
File ServerDir = new File(ServerDirPath);
if (!ServerDir.exists()) {
ServerDir.mkdirs();
}
// Giving File operation permission for LINUX//
IOperation.setFileFolderPermission(ServerDirPath);
MultipartFile originalPic = simpleLoanDto.getPic();
byte[] ImageInByte = originalPic.getBytes();
FileOutputStream fosFor = new FileOutputStream(
new File(ServerDirPath + "\\" + simpleLoanDto.getAdharNo() + "_"+simpleLoanDto.getApplicantName()+"_.jpg"));
fosFor.write(ImageInByte);
fosFor.close();
}
//End Photo Upload with No//