How to remove text from Barcode image - java

I have written a code which can generate a bar-code with respect to String codeText = "1104006"; and also can read data from that bar-code. But the problem is, while generating a bar-code below the bar-code it also write the text (codeText). How can I remove the human readable text, circled red in example?
public class Main {
private static String strBarFolder = ("C:\\Users\\Jobayer__\\Desktop\\");
public static void main(String[] args) {
String codeText = "1104006";
String strImageFile = ("barcode.jpg");
BarCodeBuilder builder = new BarCodeBuilder(Symbology.CODE39STANDARD, codeText);
builder.save(strBarFolder + strImageFile);
System.out.println("Successfully Done");
Image img = Toolkit.getDefaultToolkit().getImage(strBarFolder + strImageFile);
BarCodeReader reader = new BarCodeReader(img, BarCodeReadType.Code39Standard);
while(reader.read()){
System.out.println("Code Text Found: " + reader.getCodeText());
}
reader.close();
}
}

Get into the Aspose source code (if it's allowable) and comment out the drawString() method which is drawing the text to the image OR modify the bar code image by drawing a white rectangle with fillRect() over the text area(s) of the image.
Below is a small runnable console application I quickly whipped up that performs the latter. It is based off of the Bar Code image you provided:
package barcodetextcoverup;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.imageio.ImageIO;
public class BarCodeTextCoverUp {
public static void main(String[] args) {
startTextCover();
}
private static void startTextCover() {
Scanner scnr = new Scanner(System.in);
String userInput = "";
while (!userInput.equalsIgnoreCase("quit")) {
System.out.println("\nEnter the path and file name to the Bar Code image file\n"
+ "to modify or enter quit to exit:");
userInput = scnr.nextLine();
if (userInput.equalsIgnoreCase("quit")) { break; }
// opening a bar code image from disk
BufferedImage src = null;
try {
src = ImageIO.read(new File(userInput));
int iWidth = src.getWidth();
int iHeight = src.getHeight();
// Modify the image...
Graphics2D g2 = src.createGraphics();
g2.setColor(Color.WHITE);
//Cover the text: Aspose.Demo
g2.fillRect(0, 0, 150, 30);
// Cover the codeText at bottom of Bar Code
g2.fillRect((iWidth/2) - 75, iHeight - 40, 150, 35);
g2.dispose();
System.out.println("\nEnter a NEW path and file name for the modified Bar Code image.\n"
+ "You can use the same file name just change the extention to .png:");
userInput = scnr.nextLine();
// If nothing is supplied then the modifications are not saved.
if (!userInput.equals("")) {
ImageIO.write((RenderedImage) src, "PNG", new File(userInput));
}
System.out.println("----------------------------------------------------------------------");
} catch (IOException ex) { }
}
}
}

Set this property:
builder.CodeLocation = CodeLocation.None;
Setting CodeLocation to None will hide the barcode text thus creating
the effect of barcode without any value in it.
from Aspose support forum: https://forum.aspose.com/t/creating-2d-bar-code-using-aspose-and-merging-it-in-pdf/7265
if you want to change caption text use this property...
builder.Display2DText = "this is caption text";
By default if it's set to empty string it displays codetext.

Read the properties of bar-code methods in the below link
http://barbecue.sourceforge.net/apidocs/net/sourceforge/barbecue/Barcode.html
Using the setDrawingText(Boolean) default method we remove the text in below bar-code
Example :
Barcode barcode = BarcodeFactory.createCode128(id);
barcode.setDrawingText(false);
BarcodeImageHandler.writePNG(barcode, new FileOutputStream(new File(file Name)));

Related

Apache PDFBox - vertical match between image and text position

I need help to achieve a mapping between text and image objects in a PDF document.
As the first figure shows, my PDF documents have 3 images arranged randomly in the y-direction. To the left of them are texts. The texts extend along the height of the images.
My goal is to combine the texts into "ImObj" objects (see the class ImObj).
The 2nd figure shows that I want to use the height of the image to detect the position of the texts (all texts outside of the image height should be ignored). In the example, there will be 3 ImObj-objects formed by the 3 images.
The link to the pdf file is here (on wetransfer):
[enter link description here][3]
But my mapping does not work, because I probably use the wrong coordinates from the image. Now I have already looked at some examples, but I still don't really understand how to get the coordinates of text and images working together?
Here is my code:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import org.apache.pdfbox.util.Matrix;
public class ImExample extends PDFTextStripper {
public static void main(String[] args) {
File file = new File("C://example document.pdf");
try {
PDDocument document = PDDocument.load(file);
ImExample example = new ImExample();
for (int pnr = 0; pnr < document.getPages().getCount(); pnr++) {
PDPage page = document.getPages().get(pnr);
PDResources res = page.getResources();
example.processPage(page);
int idx = 0;
for (COSName objName : res.getXObjectNames()) {
PDXObject xObj = res.getXObject(objName);
if (xObj instanceof PDImageXObject) {
System.out.println("...add a new image");
PDImageXObject imXObj = (PDImageXObject) xObj;
BufferedImage image = imXObj.getImage();
// Here is my mistake ... but I do not know how to solve it.
ImObj imObj = new ImObj(image, idx++, pnr, image.getMinY(), image.getMinY() + image.getHeight());
example.imObjects.add(imObj);
}
}
}
example.setSortByPosition(true);
example.getText(document);
// Output
for (ImObj iObj : example.imObjects)
System.out.println(iObj.idx + " -> " + iObj.text);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<ImObj> imObjects = new ArrayList<ImObj>();
public ImExample() throws IOException {
super();
}
#Override
protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
// match between imagesize and textposition
TextPosition txtPos = textPositions.get(0);
for (ImObj im : imObjects) {
if(im.page == (this.getCurrentPageNo()-1))
if (im.minY < txtPos.getY() && (txtPos.getY() + txtPos.getHeight()) < im.maxY)
im.text.append(text + " ");
}
}
}
class ImObj {
float minY, maxY;
Image image = null;
StringBuilder text = new StringBuilder("");
int idx, page = 0;
public ImObj(Image im, int idx, int pnr, float yMin, float yMax) {
this.idx = idx;
this.image = im;
this.minY = yMin;
this.maxY = yMax;
this.page = pnr;
}
}
Best regards
You're looking for the images in the (somewhat) wrong place!
You iterate over the image XObject resources of the page itself and inspect them. But this is not helpful:
An image XObject resource merely is that, a resource. I.e. it can be used on the page, even more than once, but you cannot determine from this resource alone how it is used (where? at which scale? transformed somehow?)
There are other places an image can be stored and used on a page, e.g. in the resources of some form XObject or pattern used on the page, or inline in the content stream.
What you actually need is to parse the page content stream for uses of images and the current transformation matrix at the time of use. For a basic implementation of this have a look at the PDFBox example PrintImageLocations.
The next problem you'll run into is that the coordinates PDFBox returns in the TextPosition methods getX and getY is not from the original coordinate system of the PDF page in question but from some coordinate system normalized for the purpose of easier handling in the text extraction code. Thus, you most likely should use the un-normalized coordinates.
You can find information on that in this answer.

Rotate a BMP image in java without libraries java

This code works, it reads a file in byte type and after assigning the image it creates a copy in the directory where the other part is located with a different name, I must do the same, create a new file, I just have to make it rotate on the X and Y axes as the final 180 degree image without creating a library to do the job.
Can you help me with the code or madnar information
Thank you!
public class BMPRotations {
public static void main(String[] args) throws IOException {
int contador=0;
int datos_entrada[] = new int[921655];
try {
FileInputStream archivo_lectura = new FileInputStream("Ruta__picture.bmp");
boolean final_ar = false;
while(!final_ar) {
int byte_entrada = archivo_lectura.read();
if(byte_entrada!=-1)
datos_entrada[contador]=byte_entrada;
else
final_ar=true;
//Muestra todos los bytes
//System.out.println(datos_entrada[contador]);
contador++;
}
archivo_lectura.close();
}catch(IOException e) {
System.out.print("Error");
}
System.out.print("Bystes de la imagen: " + contador);
crea_fichero(datos_entrada);
}
static void crea_fichero(int datos_nuevo_fichero[]) {
try {
FileOutputStream fichero_nuevo = new FileOutputStream("Ruta_picture.bmp");
for(int i=0; i<datos_nuevo_fichero.length;i++) {
fichero_nuevo.write(datos_nuevo_fichero[i]);
}
fichero_nuevo.close();
}catch(IOException e) {
System.out.println("Error ");
}
}
Here is a reference image.
640X480 in 24-bit format
https://i.stack.imgur.com/pz4A4.png
This isn't a full answer but I hope it points you in right direction for what looks like homework.
What you have implemented so far is simply copying a file with hard-coded size 921655, and does not deal with an image - just any file. You could replace the entire program with:
File input = new File("Ruta__picture.bmp");
File output = new File("Ruta_picture.bmp");
Files.copy(input.toPath(), output.toPath(), StandardCopyOption.REPLACE_EXISTING);
To deal with images, look at javax.imageio.ImageIO class. This shows how to load any supported JDK image type and write it back:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
BufferedImage image = ImageIO.read(input);
// TODO: TRANSFORM "image" here
BufferedImage modified = image;
ImageIO.write(modified , "bmp", output);
Note that ImageIO.write supports other types such as "jpg".

Getting different values from getRGB and setRGB after XORing two images

I want to XOR two images pixel by pixel. I am using the following code.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.util.Scanner;
import java.security.*;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
public class sefi
{
public static void main(String[] args) throws Exception
{
encdec ed = new encdec();
String plainimagename = args[0];
String keyfilename = args[1];
String choice = args[2];
BufferedImage bikey = ImageIO.read(new File(keyfilename));
BufferedImage biplain = ImageIO.read(new File(plainimagename));
BufferedImage resizedImage = new BufferedImage(biplain.getWidth(), biplain.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(bikey, 0, 0, biplain.getWidth(), biplain.getHeight(), null);
g.dispose();
ImageIO.write(resizedImage, "jpg", new File("resizeimage.jpg"));
if(choice.equals("enc"))
{
ed.encrypt(resizedImage,biplain);
}
else if(choice.equals("dec"))
{
ed.decrypt(resizedImage,biplain);
}
}
}
class encdec
{
public void encrypt(BufferedImage bikey, BufferedImage biplain) throws Exception
{
BufferedImage xoredimage = xor(bikey, biplain);
File xored = new File("xored.jpg");
ImageIO.write(xoredimage, "JPEG", xored);
}
public void decrypt(BufferedImage bikey, BufferedImage biplain) throws Exception
{
BufferedImage xoredimage = xor(bikey, biplain);
File xored = new File("newplain.jpg");
ImageIO.write(xoredimage, "JPEG", xored);
}
private BufferedImage xor(BufferedImage image1, BufferedImage image2) throws Exception
{
BufferedImage outputimage = new BufferedImage(image1.getWidth(), image1.getHeight(), BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < image1.getHeight(); y++)
{
for (int x = 0; x < image1.getWidth(); x++)
{
outputimage.setRGB(x,y,((image1.getRGB(x, y))^(image2.getRGB(x, y))));
System.out.println("one:" + image1.getRGB(x, y) + "\ttwo:" + image2.getRGB(x, y) + "\txor:" + ((image1.getRGB(x, y))^(image2.getRGB(x, y))));
System.out.println("one:" + Integer.toBinaryString(image1.getRGB(x, y)) + "\ttwo:" + Integer.toBinaryString(image2.getRGB(x, y)) + "\txor:" + Integer.toBinaryString((image1.getRGB(x, y)^image2.getRGB(x, y))));
}
}
return outputimage;
}
}
First time I run this code where image1 is a 4-pixel colored image and image2 is a 4-pixel white image, I get the output as:
input: #java sefi white.jpg key.jpg enc
one:-201053 two:-1 xor:201052
one:11111111111111001110111010100011 two:11111111111111111111111111111111 xor:110001000101011100
one:-265579 two:-1 xor:265578
one:11111111111110111111001010010101 two:11111111111111111111111111111111 xor:1000000110101101010
one:-664247 two:-1 xor:664246
one:11111111111101011101110101001001 two:11111111111111111111111111111111 xor:10100010001010110110
one:-925624 two:-1 xor:925623
one:11111111111100011110000001001000 two:11111111111111111111111111111111 xor:11100001111110110111
Next time I run with image1 as the xored image file and image 2 as the 4-pixel colored file, which should give me the original white image as output. But I get this as output instead:
Input:#java sefi xored.jpg key.jpg dec
one:-1 two:-16773753 xor:16773752
one:11111111111111111111111111111111 two:11111111000000000000110110000111 xor:111111111111001001111000
one:-1 two:-16773753 xor:16773752
one:11111111111111111111111111111111 two:11111111000000000000110110000111 xor:111111111111001001111000
one:-1 two:-15786601 xor:15786600
one:11111111111111111111111111111111 two:11111111000011110001110110010111 xor:111100001110001001101000
one:-1 two:-15786601 xor:15786600
one:11111111111111111111111111111111 two:11111111000011110001110110010111 xor:111100001110001001101000
If you look at the output we can see that the colors of the xored image from first time has changed.
I am not able to understand why I am getting different color value for the same image file.
There's something wrong with your image selection. If you were selecting the RGB for the generated image then the first pixel would be 110001000101011100 and not 11111111000000000000110110000111.
So my advice is for you to check if you are using the correct images on the second step.
Your code looks ok, although you'd have to paste the whole code for me to have a better idea.
Found the Answer.
It is because I am using JPEG images. JPEG compresses raw image, but when it decompress it does not guarantee to produce the exact same colors as it was before compression. Thus the different color values before and after.
When I used bmp images, I got the same colors before and after.

java drawImage turns complete black

I'm pasting plenty of face images (face_50xx.png) to the one big canvas (Faces.png) using drawImage(),
but every face turns into the whole black.
Here is my source code:
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.Color;
public class maa{
static BufferedImage in;
static BufferedImage out;
public static void main(String[] args) {
String A = "face_";
String B = "png";
int j = 0;
try{
in = ImageIO.read(new File(A + 5001 + "." + B));
}
catch(java.io.IOException e){
}
out = new BufferedImage(1920, 14592, in.getType());
for(int i = 1; i < 760; i++){
String num;
j = i + 5000;
num = Integer.toString(j);
try{
in = ImageIO.read(new File("face_" + num + "." + "png"));
Graphics g = in.getGraphics();
g.drawImage(out, (i%10)*192, (i/10)*192, null);
}
catch(java.io.IOException e){
continue;
}
}
try{
ImageIO.write(out,"png",new File("Faces." + B));
}
catch(java.io.IOException e){
}
}
}
Please teach me what's the problem. Thanks.
You are doing absolutely nothing to the out image, and so when you write it to file, it will be blank.
You appear to be drawing on the wrong image. You want to get the Graphics object, g, from
the out image, and draw the in images onto out.
You should never ignore exceptions as you are doing. At least print out a stack trace:
e.g.,
catch(IOException e) {
e.printStackTrace();
}
The basic structure of your program should be:
create out image
get Out's Graphics object, g
for Loop through all of the `in` images
Draw each in image onto out using out's Graphics context, g
end for loop
dispose of g
Write the out image to file
Edit: You state in comment,
Graphics g = in.getGraphics(); is a command that transporting the in image into g, isn't it?
No, you've got things backwards. Think of the Graphics object, g, as a pen that allows you to draw onto the image that you obtained it from. So a Graphics object, g, from an in image allows me to draw on the in image.
replace:
Graphics g = in.getGraphics();
g.drawImage(out, (i%10)*192, (i/10)*192, null);
by: in.getGraphics().drawImage(out, (i%10)*192, (i/10)*192, null);

Cannot find symbol - variable mText

Hey all i have been writing some code, it allows a user to select a file, a txt file, it then reads the contents of the file and then sends the contents to a printer this case a hp 8600, but on compling i get an error, Cannot find symbol - variable mText, why is this, it should be retriving mText from above as this now should contain all the data from the txt file, what am i doing wrong ?
code:
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.text.*;
import java.io.*;
import javax.swing.*;
public class PrintText implements Printable {
// Below the code will allow the user to select a file and then print out the contents of the file
public static void main(String[] args) throws IOException {
//selects the file
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
String filename = file.getName();
//System.out.println("You have selected: " + filename); testing to see if file seleected was right
String path = file.getAbsolutePath();
//Reads contents of file into terminal
//FileReader fr = new FileReader("filename");
// FileReader fr = new FileReader("D:/Documents/" + "filename"));
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String mText;
while((mText = br.readLine()) != null) {
//Displays the contents of the file in terminal
System.out.println(mText);
}
//fr.close();
}
//private static final String mText =
// "This is a test to see if this text will be printed "; //This works perfectly fine
private static final AttributedString mStyledText = new AttributedString(mText);
/**
* Print a single page containing some sample text.
*/
static public void printer(String args[]) {
/* Get the representation of the current printer and
* the current print job.
*/
PrinterJob printerJob = PrinterJob.getPrinterJob();
/* Build a book containing pairs of page painters (Printables)
* and PageFormats. This example has a single page containing
* text.
*/
Book book = new Book();
book.append(new PrintText(), new PageFormat());
/* Set the object to be printed (the Book) into the PrinterJob.
* Doing this before bringing up the print dialog allows the
* print dialog to correctly display the page range to be printed
* and to dissallow any print settings not appropriate for the
* pages to be printed.
*/
printerJob.setPageable(book);
/* Show the print dialog to the user. This is an optional step
* and need not be done if the application wants to perform
* 'quiet' printing. If the user cancels the print dialog then false
* is returned. If true is returned we go ahead and print.
*/
boolean doPrint = printerJob.printDialog();
if (doPrint) {
try {
printerJob.print();
} catch (PrinterException exception) {
System.err.println("Printing error: " + exception);
}
}
}
/**
* Print a page of text.
*/
public int print(Graphics g, PageFormat format, int pageIndex) {
/* We'll assume that Jav2D is available.
*/
Graphics2D g2d = (Graphics2D) g;
/* Move the origin from the corner of the Paper to the corner
* of the imageable area.
*/
g2d.translate(format.getImageableX(), format.getImageableY());
/* Set the text color.
*/
g2d.setPaint(Color.black);
/* Use a LineBreakMeasurer instance to break our text into
* lines that fit the imageable area of the page.
*/
Point2D.Float pen = new Point2D.Float();
AttributedCharacterIterator charIterator = mStyledText.getIterator();
LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
float wrappingWidth = (float) format.getImageableWidth();
while (measurer.getPosition() < charIterator.getEndIndex()) {
TextLayout layout = measurer.nextLayout(wrappingWidth);
pen.y += layout.getAscent();
float dx = layout.isLeftToRight()? 0 : (wrappingWidth - layout.getAdvance());
layout.draw(g2d, pen.x + dx, pen.y);
pen.y += layout.getDescent() + layout.getLeading();
}
return Printable.PAGE_EXISTS;
}
}
Currently mText is only defined within the scope of the main method.
You would need to make mText a static class variable is you wish to use it in the constructor of mStyledText:
private static String mText;
Having non-final static class variables is considered bad practice, however—why not create AttributedString in the print method just when its needed:
AttributedString mStyledText = new AttributedString(mText);
Also you have a lot of functionality in the main method. I would move it to a class instance method where you could avoid using any static variables altogether.

Categories