I wrote a code which embeds and extracts text in an image. Despite my best attempts I was not able to understand what is wrong in the code due to which the extraction is not successful.Looking for help on the same. here is the code
public class EmbedAndExtract {
//Embedding sequence
BufferedImage embed(BufferedImage img, String s) {
int pixel[] = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());
//the manipulated pixels will be saved in newpixel[]
int[] newpixel = Arrays.copyOf(pixel, pixel.length);
int len = s.length();
int q = 0;
//each string to be embedded will be prefixed by 4 chars which contain length of string
// for a string say "abc" s1="0003abc"
//here first four chars show length of string
for (int i = 0; i < 4; i++) {
if (len % 10 == 0) {
break;
} else {
len = len / 10;
q++;
}
}
String s1 = "";
for (int i = 0; i < 4 - q; i++) {
s1 += 0;
}
s1 += s.length();
s1 += s;
// convert s1 to byte array
byte[] b = s1.getBytes();
for (int i = 0; i < b.length; i++) {
System.out.println("" + (char) b[i]);
}
//change value of newpixel[] as per the string
int count = 0;
for (int i = 0; i < b.length; i++) {
byte current_byte = b[i];
for (int j = 7; j >= 0; j--) {
int lsb = (current_byte >> j) & 1;
newpixel[count] = (pixel[count] & 0xfffffffe) + lsb;
System.out.println(lsb + ":(" + pixel[count] + "," + newpixel[count] + ")");
count++;
}
}
//add the newpixel[] to a bufferedimage and return
BufferedImage nimg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
nimg.setRGB(0, 0, nimg.getWidth(), nimg.getHeight(), newpixel, 0, nimg.getWidth());
return nimg;
}
//Extraction sequence
String extract(BufferedImage img) {
//read pixel of image
int newpixel[] = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());
//extract length from first 32 pixel values i.e it will constitute 4 bytes
String qw = "";
for (int i = 0; i < 32; i++) {
qw += (newpixel[i] & 0x00000001);
}
//convert length to integer and save it in total
int n1, n2, n3, n4, total;
n1 = Integer.parseInt(qw.substring(0, 8), 2) - 48;
n2 = Integer.parseInt(qw.substring(8, 16), 2) - 48;
n3 = Integer.parseInt(qw.substring(16, 24), 2) - 48;
n4 = Integer.parseInt(qw.substring(24, 32), 2) - 48;
total = n1 * 1000 + n2 * 100 + n3 * 10 + n4;
System.out.println("" + total);
//extract string from image and reurn string
String secret = "";
int bit = 0;
for (int i = 0; i < 4 + total; i++) {
int ascii = 0;
for (int j = 7; j >= 0; j--) {
ascii += (newpixel[bit] & 1) << j;
bit++;
}
secret += (char) ascii;
}
return secret;
}
}
the first 32 pixel values which contains length of data in embedding sequence and extracting sequence are coming to be different don't know how. If any one who can resolve the errors i wouldbe grateful.
User contributions licensed under CC BY-SA 3.0