Text added to PDF appearing bold/rough - java

I'm adding/replacing some page numbers on an existing PDF's contents page, but the text is coming out bold, or rough. It's not right any ways, and I can't seem to fix it!
This is what I mean:
The numbers on the right are the existing page numbers I am replacing and the text is fine. The numbers on the left are the page numbers I have added using iText in Java.
Here is the code:
private static void fixTOCPageNumbers(int i, PdfContentByte content, List<Section> sections)
throws DocumentException, IOException {
int xPositionRec;
int yPositionRec;
int xPositionText;
int yPositionText;
int xOffset = 0;
int yOffset = 0;
content.saveState();
content.setColorStroke(new Color(77,77,77));
content.beginText();
content.setFontAndSize(BaseFont.createFont("fonts/LTe50327.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10f);
int count = 5;
for(int j = 4; j <= sections.size() - 2; j++)
{
int startPageIndex = sections.get(j).GetStartPageIndex();
int endPageIndex = sections.get(j).GetEndPageIndex();
xPositionRec = 281;
yPositionRec = 385;
xPositionText = 266;
yPositionText = 386;
if(j > 6)
{
yPositionRec = 195;
yPositionText = 196;
}
for(int k = startPageIndex; k <= endPageIndex; k++)
{
content.rectangle(xPositionRec+xOffset,yPositionRec-yOffset,12,12);
content.setRGBColorFill(255,255,255);
content.showTextAligned(PdfContentByte.ALIGN_CENTER, String.format("%d", count), xPositionText+xOffset, yPositionText-yOffset, 0);
content.setRGBColorFill(77,77,77);
//content.fillStroke();
yOffset += 18;
count++;
}
yOffset = 0;
if(j > 6)
{
xOffset += 229;
}
else if(j == 6)
{
xOffset = 0;
}
else
{
xOffset += 230;
}
}
xOffset = 0;
yOffset = 0;
content.restoreState();
content.endText();
}
Am I doing something wrong? This is the first time I've used iText and the code base wasn't originally mine.
Any help would be much appreciated!

You can simulate bold for example like this:
C#
cb.BeginText();
cb.SetFontAndSize(font, 11F);
cb.SetCharacterSpacing(1F);
// Fill color (stroke fill)
cb.SetRGBColorFill(0, 0, 0);
cb.SetLineWidth(0.5F);
// Fill stroke simulate bold
cb.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
cb.SetTextMatrix(x, pageSize.Height - y);
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, s, (pageSize.Width / 2F), pageSize.Height - y, 0);
cb.EndText();

Related

Processing - Rough pixel sorting algorithm stops after a part of the image

I wrote a code for processing and had formerly sorted pixels with selection sort. I have to hand it in and the teacher said it is taking to long like this, so I decided to divide the pixels brightness into parts of 50 and just sort it very roughly. The image that comes out isn't completely sorted though and I really don't know where it went wrong.
I doesn't have to be sorted perfectly - it's really just about having a cool-looking image as a result.
I hope some can help me and it is understandable what I mean!
Thanks in advance
PImage img;
PImage two;
PImage sorted;
int j = 0;
int x = j;
int y = x;
int u = y;
int h = u;
int d = 1;
void setup() {
size(736,1051);
img = loadImage("guy.png");
two = loadImage("guy2.png");
background(two);
}
void draw() {
loadPixels();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int loc = x + y*width;
float r = red(img.pixels[loc]);
float g = green(img.pixels[loc]);
float b = blue(img.pixels[loc]);
float av = ((r+g+b)/3.0);
pixels[loc] = color(g,b,r, 17); //I know r, g, b are switched here
}
}
updatePixels();
save("guy_coloured.png");
}
void keyPressed(){
sorted = loadImage("guy_coloured.png");
sorted.loadPixels();
image(sorted, 0, 0);
System.out.print("doing it");
for (int i = 0; i < sorted.pixels.length; i++){
color colours = sorted.pixels[i];
float b = brightness(colours);
if(b<50){
sorted.pixels[j] = sorted.pixels[i];
j++;}
}
for (int f = 0; f < img.pixels.length; f++){
color colours = sorted.pixels[f];
float b = brightness(colours);
if(b<100 && b>50){
sorted.pixels[x] = sorted.pixels[f];
x++;}
}
for (int k = 0; k < img.pixels.length; k++){
color colours = sorted.pixels[k];
float b = brightness(colours);
if(b<150 && b>100){
sorted.pixels[y] = sorted.pixels[k];
y++;}
}
for (int t = 0; t < img.pixels.length; t++){
color colours = sorted.pixels[t];
float b = brightness(colours);
if(b<200 && b>150){
sorted.pixels[u] = sorted.pixels[t];
u++;}
}
for (int o = 0; o < img.pixels.length; o++){
color colours = sorted.pixels[o];
float b = brightness(colours);
if(b>200){
sorted.pixels[h] = sorted.pixels[o];
h++;}
}
System.out.print("done");
sorted.updatePixels();
image(sorted, 0, 0);
save("guy_sorted.png");
noLoop();
}
I want the whole image to be sorted, but it gives me back the normal image with about 1/4 sorted from the top.
This is the current result:
https://imgur.com/kHffIpm
Full code including irrelevant parts: https://docs.google.com/document/d/1YC97YMq9fKcbCAn3_RvLIm1bNo72FrNnHT3obc9pp7U/edit?usp=sharing
You do not sort the pixels. What you actually do is to arrange the dark pixel at the begin of the image and overwrite the pixels which are there. If you want to sort the pixels, then you've to swap them.
Write a function which can swap 2 pixel:
void Swap(PImage toSort, int i1, int i2) {
color c = toSort.pixels[i1];
toSort.pixels[i1] = toSort.pixels[i2];
toSort.pixels[i2] = c;
}
Once some pixels have been sorted, and are arranged at the begin of the image, this area doesn't need to be investigated further.
Write a function which sorts pixels dependent on a brightness range [b_min, b_max] and start at a certain index start:
int Sort(PImage toSort, int start, float b_min, float b_max) {
for (int i = start; i < toSort.pixels.length; i++) {
float b = brightness(toSort.pixels[i]);
if (b >= b_min && b < b_max) {
Swap(toSort, i, start);
start ++;
}
}
return start;
}
Sort the image by ascending brightness. e.g:
PImage img, two, sorted;
void setup() {
size(736,1051);
img = loadImage("guy.png");
two = loadImage("guy2.png");
background(two);
}
void draw() {
loadPixels();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int loc = x + y*width;
float r = red(img.pixels[loc]), g = green(img.pixels[loc]), b = blue(img.pixels[loc]);
pixels[loc] = color(g,b,r, 17); //I know r, g, b are switched here
}
}
updatePixels();
save("guy_coloured.png");
}
void Swap(PImage toSort, int i1, int i2) {
color c = toSort.pixels[i1];
toSort.pixels[i1] = toSort.pixels[i2];
toSort.pixels[i2] = c;
}
int Sort(PImage toSort, int start, float b_min, float b_max) {
for (int i = start; i < toSort.pixels.length; i++) {
float b = brightness(toSort.pixels[i]);
if (b >= b_min && b < b_max) {
Swap(toSort, i, start);
start ++;
}
}
return start;
}
void keyPressed(){
sorted = loadImage("guy_coloured.png");
sorted.loadPixels();
image(sorted, 0, 0);
System.out.print("doing it");
int j = 0;
j = Sort(sorted, j, 0.0, 50.0);
j = Sort(sorted, j, 0.50, 100.0);
j = Sort(sorted, j, 0.100, 150.0);
j = Sort(sorted, j, 0.150, 200.0);
j = Sort(sorted, j, 0.200, 256.0);
System.out.print("done");
sorted.updatePixels();
image(sorted, 0, 0);
save("guy_sorted.png");
noLoop();
}

How to generate QR Code with Colors for each Pixel?

I am doing a project with the QR Code. I want to change the color for each pixel.I tried but it doesn't work. Help me.
I tried: https://imgur.com/a/umE8xJ5
...
private int color_1 = 0x000000, color_2 = 0xffffffff, color_3 = Color.RED;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (bitMatrix.get(j, i)) {
if (j == 0) {
pixels[i * width + j] = color_3; // RED
} else {
pixels[i * width + j] = color_1; // BLACK
}
} else {
pixels[i * width + j] = color_2; // WHITE
}
}
}
...
I received: https://imgur.com/a/jJNrPqW
It seems that there is an existing QR code overlay.
Try setting red to 0x8F00. I think you encode the color as RGB-565, but Color.RED might be 24 bit, so there is an overflow.

How to render colours properly in Java Graphics

I was using this code placed here to generate bar-charts for my datasets. However, the colours were all the same (red in the code), so I decided to generate a colour ramp for this. I wrote the following code:
Color[] getColorRamp(int numColours)
{
Color[] colours = new Color[numColours];
int red_1 = 255;
int green_1 = 0;
int blue_1 = 0;
int red_2 = 0;
int green_2 = 0;
int blue_2 = 255;
int count = 0;
for (float t=0.0f;t<1.0f;t+=1.0/(float)numColours) {
colours[count] = new Color((int)(t*red_2 + (1-t)*red_1),
(int)(t*green_2 + (1-t)*green_1),
(int)(t*blue_2 + (1-t)*blue_1),34);
//System.out.print((int)(t*red_2 + (1-t)*red_1) +",");
//System.out.print((int)(t*green_2 + (1-t)*green_1) +",");
//System.out.println((int)(t*blue_2 + (1-t)*blue_1));
}
return colours;
}
It is here, where the problem starts. Only the first colour (pretty light blue) get rendered properly. Other colours are rendered as black! You can see that I have put System.out.println to verify the colours generated (commented in the code posted here). I saw that colours were generated as perfect RGB combinations.
The modified barchart function is posted here:
void drawBarChart(Graphics g, double[] values, String[] names, String title)
{
if (values == null || values.length == 0)
return;
double minValue = 0;
double maxValue = 0;
for (int i = 0; i < values.length; i++) {
if (minValue > values[i])
minValue = values[i];
if (maxValue < values[i])
maxValue = values[i];
}
//Graphics2D g = (Graphics2D)gg;
Dimension d = getSize();
int clientWidth = d.width;
int clientHeight = d.height;
int barWidth = clientWidth / values.length;
Font titleFont = new Font("SansSerif", Font.BOLD, 20);
FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);
int titleWidth = titleFontMetrics.stringWidth(title);
int y = titleFontMetrics.getAscent();
int x = (clientWidth - titleWidth) / 2;
g.setFont(titleFont);
g.drawString(title, x, y);
int top = titleFontMetrics.getHeight();
int bottom = labelFontMetrics.getHeight();
if (maxValue == minValue)
return;
double scale = (clientHeight - top - bottom) / (maxValue - minValue);
y = clientHeight - labelFontMetrics.getDescent();
g.setFont(labelFont);
Color[] colours = getColorRamp(values.length);
for (int i = 0; i < values.length; i++) {
int valueX = i * barWidth + 1;
int valueY = top;
int height = (int) (values[i] * scale);
if (values[i] >= 0)
valueY += (int) ((maxValue - values[i]) * scale);
else {
valueY += (int) (maxValue * scale);
height = -height;
}
g.setColor(colours[i]);
g.fillRect(valueX, valueY, barWidth - 2, height);
g.setColor(Color.black);
g.drawRect(valueX, valueY, barWidth - 2, height);
int labelWidth = labelFontMetrics.stringWidth(names[i]);
x = i * barWidth + (barWidth - labelWidth) / 2;
g.drawString(names[i], x, y);
}
//paintComponent(g);
}
I wish to know, what mistake I am making!
You're probably going to hit yourself on the head now. The reason it fails is that you forget to increase the variable count after setting the first colour, so you're constantly overwriting the first element of the Color array, and leaving all the other values in the array as their initial default (null).
Fixed code:
for (float t=0.0f;t<1.0f;t+=1.0/(float)numColours) {
colours[count++] = new Color((int)(t*red_2 + (1-t)*red_1),
(int)(t*green_2 + (1-t)*green_1),
(int)(t*blue_2 + (1-t)*blue_1),34);
}
(Notice the colours[count++])

What's wrong with this Java code for Android?

I have written this piece of code to break an image into 9 pieces and it gives me runtime error. There is no error in LogCat and I am stuck. The error comes at line 7 line from bottom (Bitmap.createBitmap(...);).
public Bitmap[] getPieces(Bitmap bmp) {
Bitmap[] bmps = new Bitmap[9];
int width = bmp.getWidth();
int height = bmp.getHeight();
int rows = 3;
int cols = 3;
int cellHeight = height / rows;
int cellWidth = width / cols;
int piece = 0;
for (int x = 0; x <= width; x += cellWidth) {
for (int y = 0; y <= height; y += cellHeight) {
Bitmap b = Bitmap.createBitmap(bmp, x, y, cellWidth,
cellHeight, null, false);
bmps[piece] = b;
piece++;
}
}
return bmps;
}
It is a limitation of android framework which doesn't give proper error message. The ideal solution would be to wrap your code in try / catch block and log the exception to console and fix your code accordingly, but use it only for debugging purposes.
try {
// Code
}
catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE:"+e.toString());
}
The above code extracted from here:
http://moazzam-khan.com/blog/?p=41
Instead of
for (int x = 0; x <= width; x += cellWidth) {
for (int y = 0; y <= height; y += cellHeight) {
use
for (int x = 0; x+cellWidth < width; x += cellWidth) {
for (int y = 0; y+cellHeight < height; y += cellHeight) {
to avoid fetching parts of the image that (at least partly) don't exist.
In your code, piece can be greater than 8, so you are getting index out of bounds on bmps. You need to rewrite it so that the right-most and bottom-most pieces just have all of the extra and aren't necessarily the same size.
Or, if you need them to be the same size, drop the extra rows/cols. To make sure, I would formulate my for loop like this
for (int cellX = 0; cellX < 3; cellX++) {
int x = cellX * cellWidth;
for (int cellY = 0; cellY < 3; cellY++) {
int y = cellY * cellHeight;
// find the cellWidth/Height that doesn't overflow the original image
Bitmap b = // get the bitmap
bmps[piece] = b;
piece++;
}
}

Crop image to smallest size by removing transparent pixels in java

I have a sprite sheet which has each image centered in a 32x32 cell. The actual images are not 32x32, but slightly smaller. What I'd like to do is take a cell and crop the transparent pixels so the image is as small as it can be.
How would I do that in Java (JDK 6)?
Here is an example of how I'm currently breaking up the tile sheet into cells:
BufferedImage tilesheet = ImageIO.read(getClass().getResourceAsStream("/sheet.png");
for (int i = 0; i < 15; i++) {
Image img = tilesheet.getSubimage(i * 32, 0, 32, 32);
// crop here..
}
My current idea was to test each pixel from the center working my way out to see if it is transparent, but I was wondering if there would be a faster/cleaner way of doing this.
There's a trivial solution – to scan every pixel. The algorithm bellow has a constant performance of O(w•h).
private static BufferedImage trimImage(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int top = height / 2;
int bottom = top;
int left = width / 2 ;
int right = left;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (image.getRGB(x, y) != 0){
top = Math.min(top, y);
bottom = Math.max(bottom, y);
left = Math.min(left, x);
right = Math.max(right, x);
}
}
}
return image.getSubimage(left, top, right - left + 1, bottom - top + 1);
}
But this is much more effective:
private static BufferedImage trimImage(BufferedImage image) {
WritableRaster raster = image.getAlphaRaster();
int width = raster.getWidth();
int height = raster.getHeight();
int left = 0;
int top = 0;
int right = width - 1;
int bottom = height - 1;
int minRight = width - 1;
int minBottom = height - 1;
top:
for (;top <= bottom; top++){
for (int x = 0; x < width; x++){
if (raster.getSample(x, top, 0) != 0){
minRight = x;
minBottom = top;
break top;
}
}
}
left:
for (;left < minRight; left++){
for (int y = height - 1; y > top; y--){
if (raster.getSample(left, y, 0) != 0){
minBottom = y;
break left;
}
}
}
bottom:
for (;bottom > minBottom; bottom--){
for (int x = width - 1; x >= left; x--){
if (raster.getSample(x, bottom, 0) != 0){
minRight = x;
break bottom;
}
}
}
right:
for (;right > minRight; right--){
for (int y = bottom; y >= top; y--){
if (raster.getSample(right, y, 0) != 0){
break right;
}
}
}
return image.getSubimage(left, top, right - left + 1, bottom - top + 1);
}
This algorithm follows the idea from pepan's answer (see above) and is 2 to 4 times more effective. The difference is: it never scans any pixel twice and tries to contract search range on each stage.
The worst case of the method's performance is O(w•h–a•b)
This code works for me. The algorithm is simple, it iterates from left/top/right/bottom of the picture and finds the very first pixel in the column/row which is not transparent. It then remembers the new corner of the trimmed picture and finally it returns the sub image of the original image.
There are things which could be improved.
The algorithm expects, there is the alpha byte in the data. It will fail on an index out of array exception if there is not.
The algorithm expects, there is at least one non-transparent pixel in the picture. It will fail if the picture is completely transparent.
private static BufferedImage trimImage(BufferedImage img) {
final byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
int width = img.getWidth();
int height = img.getHeight();
int x0, y0, x1, y1; // the new corners of the trimmed image
int i, j; // i - horizontal iterator; j - vertical iterator
leftLoop:
for (i = 0; i < width; i++) {
for (j = 0; j < height; j++) {
if (pixels[(j*width+i)*4] != 0) { // alpha is the very first byte and then every fourth one
break leftLoop;
}
}
}
x0 = i;
topLoop:
for (j = 0; j < height; j++) {
for (i = 0; i < width; i++) {
if (pixels[(j*width+i)*4] != 0) {
break topLoop;
}
}
}
y0 = j;
rightLoop:
for (i = width-1; i >= 0; i--) {
for (j = 0; j < height; j++) {
if (pixels[(j*width+i)*4] != 0) {
break rightLoop;
}
}
}
x1 = i+1;
bottomLoop:
for (j = height-1; j >= 0; j--) {
for (i = 0; i < width; i++) {
if (pixels[(j*width+i)*4] != 0) {
break bottomLoop;
}
}
}
y1 = j+1;
return img.getSubimage(x0, y0, x1-x0, y1-y0);
}
I think this is exactly what you should do, loop through the array of pixels, check for alpha and then discard. Although when you for example would have a star shape it will not resize the image to be smaller be aware of this.
A simple fix for code above. I used the median for RGB and fixed the min() function of x and y:
private static BufferedImage trim(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int top = height / 2;
int bottom = top;
int left = width / 2 ;
int right = left;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (isFg(img.getRGB(x, y))){
top = Math.min(top, y);
bottom = Math.max(bottom, y);
left = Math.min(left, x);
right = Math.max(right, x);
}
}
}
return img.getSubimage(left, top, right - left, bottom - top);
}
private static boolean isFg(int v) {
Color c = new Color(v);
return(isColor((c.getRed() + c.getGreen() + c.getBlue())/2));
}
private static boolean isColor(int c) {
return c > 0 && c < 255;
}
[Hi I tried the following. In the images file idle1.png is the image with a big transparent box while testing.png is the same image with minimum bounding box
'BufferedImage tempImg = (ImageIO.read(new File(fileNPath)));
WritableRaster tempRaster = tempImg.getAlphaRaster();
int x1 = getX1(tempRaster);
int y1 = getY1(tempRaster);
int x2 = getX2(tempRaster);
int y2 = getY2(tempRaster);
System.out.println("x1:"+x1+" y1:"+y1+" x2:"+x2+" y2:"+y2);
BufferedImage temp = tempImg.getSubimage(x1, y1, x2 - x1, y2 - y1);
//for idle1.png
String filePath = fileChooser.getCurrentDirectory() + "\\"+"testing.png";
System.out.println("filePath:"+filePath);
ImageIO.write(temp,"png",new File(filePath));
where the get functions are
public int getY1(WritableRaster raster) {
//top of character
for (int y = 0; y < raster.getHeight(); y++) {
for (int x = 0; x < raster.getWidth(); x++) {
if (raster.getSample(x, y,0) != 0) {
if(y>0) {
return y - 1;
}else{
return y;
}
}
}
}
return 0;
}
public int getY2(WritableRaster raster) {
//ground plane of character
for (int y = raster.getHeight()-1; y > 0; y--) {
for (int x = 0; x < raster.getWidth(); x++) {
if (raster.getSample(x, y,0) != 0) {
return y + 1;
}
}
}
return 0;
}
public int getX1(WritableRaster raster) {
//left side of character
for (int x = 0; x < raster.getWidth(); x++) {
for (int y = 0; y < raster.getHeight(); y++) {
if (raster.getSample(x, y,0) != 0) {
if(x > 0){
return x - 1;
}else{
return x;
}
}
}
}
return 0;
}
public int getX2(WritableRaster raster) {
//right side of character
for (int x = raster.getWidth()-1; x > 0; x--) {
for (int y = 0; y < raster.getHeight(); y++) {
if (raster.getSample(x, y,0) != 0) {
return x + 1;
}
}
}
return 0;
}'[Look at Idle1.png and the minimum bounding box idle = testing.png][1]
Thank you for your help regards Michael.Look at Idle1.png and the minimum bounding box idle = testing.png]images here
If your sheet already has transparent pixels, the BufferedImage returned by getSubimage() will, too. The default Graphics2D composite rule is AlphaComposite.SRC_OVER, which should suffice for drawImage().
If the sub-images have a distinct background color, use a LookupOp with a four-component LookupTable that sets the alpha component to zero for colors that match the background.
I'd traverse the pixel raster only as a last resort.
Addendum: Extra transparent pixels may interfere with collision detection, etc. Cropping them will require working with a WritableRaster directly. Rather than working from the center out, I'd start with the borders, using a pair of getPixels()/setPixels() methods that can modify a row or column at a time. If a whole row or column has zero alpha, mark it for elimination when you later get a sub-image.

Categories