In above code i want to use custom font (which is commented on code), when i use commented font1 then iam not getting output properly.
BufferedImage source = ImageIO.read(input_file);
File backImg = new File("C:\\Users\\saradhi\\Desktop\\water-lily-3784022__340.jpg");
BufferedImage backImgB = ImageIO.read(backImg);
final BufferedImage textImage = new BufferedImage(
backImgB.getWidth(),
backImgB.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = textImage.createGraphics();
FontRenderContext frc = g.getFontRenderContext();
/*
* Font font1 = Font.createFont(Font.TRUETYPE_FONT, new
* File("C:\\Users\\saradhi\\Desktop\\Pacifico.ttf")); font1.deriveFont(9f);
*/
Font font = new Font(Font.SANS_SERIF, Font.BOLD, 120);
GlyphVector gv = font.createGlyphVector(frc, name);
Rectangle2D box = gv.getVisualBounds();
int xOff = 25 + (int) - box.getX();
int yOff = 80 + (int) - box.getY();
Shape shape = gv.getOutline(xOff, yOff);
g.setClip(shape);
g.drawImage(backImgB, 0, 0, null);
g.setClip(null);
g.setStroke(new BasicStroke(2 f));
g.setColor(Color.BLACK);
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.draw(shape);
g.dispose();
File file = new File("cat-text.png");
ImageIO.write(textImage, "png", new File("C:\\Users\\saradhi\\Desktop\\resultEX.jpeg"));
i get the custom font through this code
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("C:\\Pacifico.ttf"))
.deriveFont(48 f);
Related
I have generated QR code using com.google.zxing this library.
QRCode generations work fine but I want to display Data of QRcode below QRcode.
I want to generate QR code like attached below.
Here is my code.
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
byte[] pngData = pngOutputStream.toByteArray();
Here I have Provided complete code for generating QRcode with Text or not.
public byte[] generateQRCode(String data, Integer width, Integer height, String[] text) {
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
byte[] pngData = pngOutputStream.toByteArray();
// If text is needed to display
if (text.length > 0) {
int totalTextLineToadd = text.length;
InputStream in = new ByteArrayInputStream(pngData);
BufferedImage image = ImageIO.read(in);
BufferedImage outputImage = new BufferedImage(image.getWidth(), image.getHeight() + 25 * totalTextLineToadd, BufferedImage.TYPE_INT_ARGB);
Graphics g = outputImage.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, outputImage.getWidth(), outputImage.getHeight());
g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
g.setFont(new Font("Arial Black", Font.BOLD, 12));
Color textColor = Color.BLACK;
g.setColor(textColor);
FontMetrics fm = g.getFontMetrics();
int startingYposition = height + 5;
for(String displayText : text) {
g.drawString(displayText, (outputImage.getWidth() / 2) - (fm.stringWidth(displayText) / 2), startingYposition);
startingYposition += 20;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(outputImage, "PNG", baos);
baos.flush();
pngData = baos.toByteArray();
baos.close();
}
return pngData;
} catch (WriterException | IOException ex) {
throw new ImtechoUserException(ex.getMessage(), 0);
}
}
This will return Byte[] of newly generated QR code with text or without text.
Here I Generated QR Code file and took in memory and then used Graphics Lib.
Using this Library could add Text to that Memory and saved it again.
public static void main(String[] args) {
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode("Hello world", BarcodeFormat.QR_CODE, 300, 300);
Path path = FileSystems.getDefault().getPath("test.png");
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
final BufferedImage image = ImageIO.read(new File(path.toString()));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(22f));
Color textColor = Color.BLACK;
g.setColor(textColor);
g.drawString("Hello world", 15, 300);
g.dispose();
ImageIO.write(image, "png", new File("test45.png"));
} catch (WriterException | IOException ex) {
}
}
#Ashish Khokhariya thank you i do it withe your code
I am sorry I cant " feedback " :
Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.
The below code worked for me.
public BufferedImage getQRCodeWithText(BitMatrix qrcodeBitMatrix, String text) throws IOException {
BufferedImage image = MatrixToImageWriter.toBufferedImage(qrcodeBitMatrix);
if (text.length() > 0) {
int totalTextLineToAdd = text.length();
int newWidth = image.getWidth();
int newHeight = image.getHeight() + 10 * totalTextLineToAdd;
BufferedImage newImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = newImage.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, newImage.getWidth(), newImage.getHeight());
graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
graphics.setFont(new Font("Arial Black", Font.BOLD, 12));
Color textColor = Color.BLACK;
graphics.setColor(textColor);
FontMetrics fontMetrics = graphics.getFontMetrics();
int startingYPosition = image.getHeight() + 5;
graphics.drawString(text, (newImage.getWidth() / 2) - (fontMetrics.stringWidth(text) / 2), startingYPosition);
image = newImage;
}
return image;
}
I am trying to create a Plagiarism checker software. Till now I have created a buffered Image which converts any text written in an text area into a png,jpg,jpeg, gif format.
When I open the image text written inside the image is shown too small and it is shown properly only when I manually zoom my screen from keyboard or Mouse.
I have tried several techniques to zoom out or reposition the image but failed. How could I achieve a zoomed in image?
Here is my Code.
String text = textArea.getText();
Font font = new Font("Tahoma", Font.PLAIN, 40);
FontRenderContext frc = new FontRenderContext(null, true, true);
//get the height and width of the text
Rectangle2D bounds = font.getStringBounds(text, frc);
int w = (int) bounds.getWidth();
int h = (int) bounds.getHeight();
String[] parts = text.split("\n");
//create a BufferedImage object
BufferedImage img = new BufferedImage(w, h * parts.length, BufferedImage.TYPE_INT_RGB);
//calling createGraphics() to get the Graphics2D
Graphics2D g = img.createGraphics();
//set color and other parameters
g.setColor(Color.WHITE);
g.setFont(font);
int index = 0;
for(String part : parts){
g.drawString(part, 4000, h * index++);
}
g.dispose();
I am using itext liberary for pdf generation in mine JavaFX project.Now i want's to print hindi , punjabi text from database inside report , How can i do this. However IText library is not recognise hindi and punjabi unicode ???
here is mine code
out = new ByteArrayOutputStream();
try {
// initialize document with page size and margins
document = new Document(PageSize.A4, 60, 40, 60, 60);
this.setAlignmentOfCompanyInfo(Common.comp
.getReportsHeaderAlignment());
writer = PdfWriter.getInstance(document, out);
writer.setPageEvent(new PageEventForAddressBookReport());
document.open();PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(w, h);
#SuppressWarnings("deprecation")
Graphics2D g2 = tp.createGraphicsShapes(w, h);
g2.drawString("वर्तमान शेष", 200, 100);
g2.dispose();
g2.setColor(Color.GREEN);
cb.addTemplate(tp, 50, 400);
BufferedImage bi = new BufferedImage(100, 20, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2 = bi.createGraphics();
ImageIO.write(bi, "PNG", new File("ourImageName.PNG"));
Image image = Image.getInstance(tp);
document.add(new Chunk(image,5,5));
document.close();
As itext is not supporting vernacular language, convert text to bitmap and set as image. Use below method for conversion:
public Bitmap textAsBitmap(String text, float textSize, float stroke,
int color) {
TextPaint paint = new TextPaint();
paint.setTextSize(textSize);
paint.setAntiAlias(true);
// paint.setTextAlign(Paint.Align.LEFT);
paint.setAntiAlias(true);
paint.setColor(color);
// paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(20f);
paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
float baseline = (int) (-paint.ascent() + 3f); // ascent() is negative
StaticLayout staticLayout = new StaticLayout(text, 0, text.length(),
paint, 435, android.text.Layout.Alignment.ALIGN_NORMAL, 1.0f,
1.0f, false);
// int linecount = staticLayout.getLineCount();
//
// int height = (int) (baseline + paint.descent() + 3) * linecount + 10;
Bitmap image = Bitmap.createBitmap(staticLayout.getWidth(),
staticLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
// canvas.drawARGB(100, 100, 100, 100);
staticLayout.draw(canvas);
return image;
}
It's never a good idea to add the text in a notation that isn't Unicode, but that's not the main problem. The main problem is that you aren't providing the right font. You need a font that knows how to draw Indic glyphs. Arial Unicode MS is such a font:
String text = "\u0936\u093e\u0902\u0924\u093f";
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(100, 50);
Graphics2D g2 = tp.createGraphicsShapes(100, 50);
java.awt.Font font = new java.awt.Font(
"Arial Unicode MS", java.awt.Font.PLAIN, 12);
g2.setFont(font);
g2.drawString("Graphics2D: " + text, 0, 40);
g2.dispose();
cb.addTemplate(tp, 36, 750);
Note that this assumes that Java has access to the font arialuni.ttf.
i am using hindi text to be appear in PDf as below
BaseFont unicode = BaseFont.createFont("/home/mani/Documents/Back up (works)/Devanagari/Devanagari.ttf",
BaseFont.COURIER, BaseFont.EMBEDDED);
Font font=new Font(unicode,12,Font.NORMAL,new BaseColor(50,205,50));
table = new PdfPTable(new float[] { 10, 60, 30 });
table.setWidthPercentage(100);
PdfPCell customerLblCell = new PdfPCell(new Phrase("karent balance",
font));
Its working fine in mine case .
I was looking for a way to rearrange several arguments recived as strings and one byte[] image and put them all togther as one image (jpg for example) ready to be printed (immidiatly).
example:
public static void printCard(String name, String LName, Image MainImage)
Basicly this function will be a simple card printer.
I was looking for an idea or some one who can guide me, this could be very easy if some one will guide me a bit.
This is a simple method that I use to add text onto a pre-existing image.
I'm sure you can work out how to pass a blank image in and add the other lines as you see fit.
private BufferedImage drawText2(BufferedImage bi, String outputText) {
Graphics2D g2d = bi.createGraphics();
g2d.setFont(new Font("Helvetica", Font.BOLD, 36));
FontMetrics fm = g2d.getFontMetrics();
int textWidth = fm.stringWidth(outputText);
int imageWidth = bi.getWidth();
int leftAlignment;
int topAlignment;
// Align the text to the middle
leftAlignment = (imageWidth / 2) - (textWidth / 2);
// Align the text to the top
topAlignment = fm.getHeight() - 10;
// Create the drop shadow
g2d.setColor(Color.DARK_GRAY);
g2d.drawString(outputText, leftAlignment + 2, topAlignment + 2);
// Create the text itself
g2d.setColor(Color.LIGHT_GRAY);
g2d.drawString(outputText, leftAlignment, topAlignment);
g2d.dispose();
return bi;
}
If you want to print directly from your application you can use
java.awt.print package.
Try this method
public static void printCard(final String name, final String lName, final Image mainImage){
Printable contentToPrint = new Printable(){
#Override
public int print(Graphics graphics, PageFormat pageFormat, int page) throws PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
pageFormat.setOrientation(PageFormat.PORTRAIT);
graphics.drawImage(mainImage, 0, 0, null);
graphics.drawString(lName, 100, 300);
graphics.drawString(name, 100, 100);
return PAGE_EXISTS;
}
};
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(contentToPrint);
//You can show a print dialog before printing by job by wrapping the following blocks with a conditional statement if(job.printDialog()){...}
try {
job.print();
} catch (PrinterException e) {
System.err.println(e.getMessage());
}
}
You need to import the print related classes from java.awt.print.
i used graphics2d to impliment my function . this method recive 2 images and 6 strings :
Bufferdimage bi is my blank image, on this image i add objects (ex: image, string) :
private static BufferedImage drawText2(BufferedImage logo,BufferedImage small,BufferedImage bi, String Headline,String outputText2,String outputText3,String outputText4,String outputText5,String outputText6) {
Graphics2D g2d = bi.createGraphics();
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g2d.setRenderingHints(rh);
g2d.setFont(new Font("Arial", Font.BOLD, 50));
FontMetrics fm = g2d.getFontMetrics();
int textWidth = fm.stringWidth(Headline);
int imageWidth = bi.getWidth();
int leftAlignment;
int topAlignment;
// Align the text to the top
topAlignment = fm.getHeight() - 10;
// Create the text itself
//headline
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.blue);
g2d.drawString(Headline, leftAlignment+290, topAlignment+60);
//property changed
g2d.setFont(new Font("Arial", Font.BOLD, 30));
fm = g2d.getFontMetrics();
textWidth = fm.stringWidth(Headline);
//second line
textWidth = fm.stringWidth(outputText2);
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.black);
g2d.drawString(outputText2, leftAlignment+290, topAlignment+120);
//third line
textWidth = fm.stringWidth(outputText3);
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.black);
g2d.drawString(outputText3, leftAlignment+290, topAlignment+160);
//4 line
textWidth = fm.stringWidth(outputText4);
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.black);
g2d.drawString(outputText4, leftAlignment+290, topAlignment+200);
//5 line
textWidth = fm.stringWidth(outputText5);
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.black);
g2d.drawString(outputText5, leftAlignment+290, topAlignment+240);
//property changed
g2d.setFont(new Font("Arial", Font.getFont("Arial").HANGING_BASELINE, 20));
fm = g2d.getFontMetrics();
//security line
textWidth = fm.stringWidth(outputText6);
leftAlignment = (textWidth);
g2d.setColor(Color.red);
g2d.drawString(outputText6, 10, topAlignment+300);
//logo
g2d.drawImage (logo, 44, 44,180,70, null);
//profile
g2d.drawImage (small, 60, 120,160,190, null);
g2d.dispose();
return bi;
}
bi is the card with all other objects
btw i added smothing to the font, without this the text is very unpleasent.
Im creating a servlet that renders a jpg/png with a given text. I want the text to be centered on the rendered image. I can get the width, but the height i'm getting seems to be wrong
Font myfont = new Font(Font.SANS_SERIF, Font.BOLD, 400);
BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setFont(myfont);
g.setColor(Color.BLACK);
FontMetrics fm = g.getFontMetrics();
Integer textwidth = fm.stringWidth(imagetext);
Integer textheight = fm.getHeight();
FontRenderContext fr = g.getFontRenderContext();
LineMetrics lm = myfont.getLineMetrics("5", fr );
float ascent = lm.getAscent();
float descent = lm.getDescent();
float height = lm.getHeight();
g.drawString("5", ((imagewidth - textwidth) / 2) , y?);
g.dispose();
ImageIO.write(image, "png", outputstream);
These are the values I get:
textwidth = 222
textheight = 504
ascent = 402
descent = 87
height = 503
Anyone know how to get the exact height om the "5" ? The estimated height should be around 250
It's still a bit off, but much closer (288): ask the Glyph (the actual graphical representation)
GlyphVector gv = myfont.createGlyphVector(fr, "5");
Rectangle2D bounds = gv.getGlyphMetrics(0).getBounds2D();
float height = bounds.height();
Other Glyph methods (getGlyphVisualBounds, getGlyphPixelBounds, ...) return the same value. This is the region of the affected pixels when the glyph is drawn, so you won't get a better value IMO
FontRenderContext frc = gc.getFontRenderContext();
float textheight = (float) font.getStringBounds(comp.text, frc).getHeight();