Cannot read image in jar - java

i have written a program to encrypt an image in Netbeans. The program works fine when running from netbeans but when i build it into a .jar file its not working, it cannot read the image even though i placed the image file in the same folder as the .jar file.
package test;
import java.io.IOException;
import java.io.File;
/**
*
* #author AMaR
*/
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, Exception {
File EnImage = new File("encrypted.png");
File DeImage = new File("decrypted.png");
int[] pixels;
LoadImage l = new LoadImage();
l.load();
pixels= l.getImagePixels();
RC4New rc4 = new RC4New();
int key[]= {13,2,4,6,};
// int data[]={5,10,90,5};
rc4.KSA(key);
int[] text = rc4.PRNG(pixels);
l.write((int)512,(int)512,text,EnImage);
//RC4New rc41 = new RC4New();
rc4.KSA(key);
int[] text1 = rc4.PRNG(text);
l.write((int)512,(int)512,text1,DeImage);
/* for(int i=0;i<text.length;i++){
System.out.println(text[i]);
}
RC4New rc41 = new RC4New();
rc4.KSA(key);
int[] text1 = rc4.PRNG(text);
for(int i=0;i<text1.length;i++){
System.out.println(text1[i]);
}
*/
System.out.println("length:"+pixels.length);
// l.write((int)512,(int)512,text);
// TODO code application logic here
}
}
//encryption
package test;
/**
*
* #author AMaR
*/
public class RC4New {
int state[] = new int[256];
int j;
/**
*
* #param key
*/
public void KSA(int[] key){
int tmp;
for (int i=0; i < 256; i++) {
state[i] = i;
}
j=0;
for (int i=0; i < 256; i++) {
j = (j + state[i] + key[i % key.length]) % 256;
tmp = state[i];
state[i] = state[j];
state[j] = tmp;
}
}
public int[] PRNG(int[] data){
int tmp,k;
int i=0;
j=0;
int[] cipherText = new int[data.length];
for(int x=0;x<data.length;x++){
i = (i + 1) % 256;
j = (j + state[i]) % 256;
tmp = state[i];
state[i] = state[j];
state[j] = tmp;
k = state[(state[i] + state[j]) % 256];
cipherText[x]= (data[x] ^ k);
}
return cipherText;
}
}
//loading/writing image
package test;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.image.WritableRaster;
/**
*
* #author AMaR
*/
public class LoadImage {
BufferedImage image;
void load()throws Exception {
// FIle newfile = new File("lena.png)
image = ImageIO.read(getClass().getResourceAsStream("lena.png"));
}
public Dimension getImageSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
public int[] getImagePixels() {
int [] dummy = null;
int wid, hgt;
// compute size of the array
wid = image.getWidth();
hgt = image.getHeight();
// start getting the pixels
Raster pixelData;
pixelData = image.getData();
return pixelData.getPixels(0, 0, wid, hgt, dummy);
}
#SuppressWarnings("empty-statement")
public void write(int width ,int height, int[] pixels,File outputfile) {
try {
// retrieve image
BufferedImage writeImage = new BufferedImage(512, 512, BufferedImage.TYPE_BYTE_GRAY);;
// File outputfile = new File("encrypted.png");
WritableRaster raster = (WritableRaster) writeImage.getData();
raster.setPixels(0,0,width,height,pixels);
writeImage.setData(raster);
ImageIO.write(writeImage, "png", outputfile);
} catch (IOException e) {
}
}
}

It's not clear which of the below is triggering your error. This
File EnImage = new File("encrypted.png");
will read from the current directory, which is not necessarily the same directory as that your jar file is in.
This
image = ImageIO.read(getClass().getResourceAsStream("lena.png"));
will read from the directory in the jar file that your class is in. Note that you're reading from the jar file, not the directory.
Given the above code, I would:
determine or explicitly specify the working directory for the File() operations. Your working directory is the one you invoke java from, and this may differ within/without the IDE
package the lena.png as a resource within your .jar file.

Related

Given a 200x200 RGB PNG file , extract the 2 least significant bits of each pixel data to create a new 200x200 image saved to disk

Here is the code, I am getting black image.
package example;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class imageCopy {
public static void main(String[] args) {
BufferedImage img = null;
File f = null;
try {
f = new File("E:\\unnamed.png");
img = ImageIO.read(f);
}catch(Exception e) {
e.printStackTrace();
}
int width = img.getWidth();
int height = img.getHeight();
for(int i=0;i<height;i++) {
for(int j=0;j<width;j++) {
int p = img.getRGB(j, i);
int k = p << -2 >>> -2;
img.setRGB(j, i, k);
}
}
try {
f = new File("E:\\Output.png");
ImageIO.write(img, "png", f);
}catch(Exception e) {
e.printStackTrace();
}
}
}
png

Unable to down scale gray scale image

I have an grayscale image with dimension 256*256.I am trying to downscale it to 128*128.
I am taking an average of two pixel and writing it to the ouput file.
class Start {
public static void main (String [] args) throws IOException {
File input= new File("E:\\input.raw");
File output= new File("E:\\output.raw");
new Start().resizeImage(input,output,2);
}
public void resizeImage(File input, File output, int downScaleFactor) throws IOException {
byte[] fileContent= Files.readAllBytes(input.toPath());
FileOutputStream stream= new FileOutputStream(output);
int i=0;
int j=1;
int result=0;
for(;i<fileContent.length;i++)
{
if(j>1){
// skip the records.
j--;
continue;
}
else {
result = fileContent[i];
for (; j < downScaleFactor; j++) {
result = ((result + fileContent[i + j]) / 2);
}
j++;
stream.write( fileContent[i]);
}
}
stream.close();
}
}
Above code run successfully , I can see the size of output file size is decreased but when I try to convert
output file (raw file) to jpg online (https://www.iloveimg.com/convert-to-jpg/raw-to-jpg) it is giving me an error saying that file is corrupt.
I have converted input file from same online tool it is working perfectly. Something is wrong with my code which is creating corrupt file.
How can I correct it ?
P.S I can not use any library which directly downscale an image .
Your code is not handling image resizing.
See how-to-resize-images-in-java.
Which, i am copying a simple version here:
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageResizer {
public static void resize(String inputImagePath,
String outputImagePath, int scaledWidth, int scaledHeight)
throws IOException {
// reads input image
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
// creates output image
BufferedImage outputImage = new BufferedImage(scaledWidth,
scaledHeight, inputImage.getType());
// scales the input image to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// extracts extension of output file
String formatName = outputImagePath.substring(outputImagePath
.lastIndexOf(".") + 1);
// writes to output file
ImageIO.write(outputImage, formatName, new File(outputImagePath));
}
public static void resize(String inputImagePath,
String outputImagePath, double percent) throws IOException {
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
int scaledWidth = (int) (inputImage.getWidth() * percent);
int scaledHeight = (int) (inputImage.getHeight() * percent);
resize(inputImagePath, outputImagePath, scaledWidth, scaledHeight);
}
public static void main(String[] args) {
String inputImagePath = "resources/snoopy.jpg";
String outputImagePath1 = "target/Puppy_Fixed.jpg";
String outputImagePath2 = "target/Puppy_Smaller.jpg";
String outputImagePath3 = "target/Puppy_Bigger.jpg";
try {
// resize to a fixed width (not proportional)
int scaledWidth = 1024;
int scaledHeight = 768;
ImageResizer.resize(inputImagePath, outputImagePath1, scaledWidth, scaledHeight);
// resize smaller by 50%
double percent = 0.5;
ImageResizer.resize(inputImagePath, outputImagePath2, percent);
// resize bigger by 50%
percent = 1.5;
ImageResizer.resize(inputImagePath, outputImagePath3, percent);
} catch (IOException ex) {
System.out.println("Error resizing the image.");
ex.printStackTrace();
}
}
}

RC4 image encryption/Decryption

I am trying to carry out Image Encryption/Decryption process.The code is running without any errors but the output is not correct. I am unable to determine where I am going wrong.
The same code is used for both encryption and decryption. The only difference being the change of path as input.
PS: I am a new to java and image handling concepts.
package crptography;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
public class RC4Final {
public static int s[]=new int[256];
public static int t;
public static void main(String args[])throws IOException
{
int i=0,j=0,temp=0;
String key;
int k[]=new int[256];
String path = "C:\\rc4\\Koala.jpg";
//String path = "C:\\rc4\\encrypted.jpg";
BufferedImage old_img = null;
try { old_img = ImageIO.read(new File(path));}
catch (Exception e) { e.printStackTrace(); }
BufferedImage new_img = new BufferedImage( old_img.getWidth(),
old_img.getHeight(),
BufferedImage.TYPE_INT_RGB);
int n = new_img.getWidth();
int m = new_img.getHeight();
//initialization array s
DataInputStream in=new DataInputStream(System.in);
System.out.print("\n\nENTER KEY TEXT\t\t");
key = in.readLine();
char keyc[]=key.toCharArray();
int keyi[]=new int[key.length()];
for(int a=0;a<key.length();a++)
{
keyi[a]=(int)keyc[a];
}
for( i=0;i<255;i++)
{
s[i]=i;
k[i]=keyi[i%key.length()];
}
//end
//initial permutation of array s
j=0;
for( i=0;i<255;i++)
{
j = (j+s[i]+k[i])%256;
temp = s[i];
s[i]=s[j];
s[j]=temp;
}
//end
//encryption start
i=0;
j=0;
int t1;
int red,green,blue,cr,cg,cb;
int rgb ;
for ( i = 0; i < n; ++i)
{
for ( j = 0; j < m; ++j)
{
rgb = old_img.getRGB(i,j);
blue = (rgb)&0xFF;
green = (rgb>>8)&0xFF;
red = (rgb>>16)&0xFF;
t1= permutate(i,j);
cr=s[t1]^red;
t1= permutate(i,j);
cg=s[t1]^green;
t1=permutate(i,j);
cb=s[t1]^blue;
int rgb1=new Color(cr, cg, cb).getRGB();
new_img.setRGB(i, j, rgb1);
}
}
saveToFile( new_img, new File( "C:\\rc4\\encrypted.jpg" ) );
//saveToFile( new_img, new File( "C:\\rc4\\decrypted.jpg" ) );
}
//permute method
public static int permutate(int x,int y)
{
int temp;
x=(x+1)%256;
y=(y+s[x])%256;
temp = s[x];
s[x]=s[y];
s[y]=temp;
t = s[(s[x]+s[y])%256];
return t;
}
//end
public static void saveToFile( BufferedImage img, File file ) throws IOException {
ImageWriter writer = null;
java.util.Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
if( iter.hasNext() ){
writer = (ImageWriter)iter.next();
}
ImageOutputStream ios = ImageIO.createImageOutputStream( file );
writer.setOutput(ios);
ImageWriteParam param = new JPEGImageWriteParam( java.util.Locale.getDefault() );
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
param.setCompressionQuality(0.98f);
writer.write(null, new IIOImage( img, null, null ), param);
}
}

how to convert image from coordinate x,y values in java?

In my project we need spot the difference among a set of images,so at first i tried it for three images and I have written code to differentiate between three images based on RGB values.I have stored coordinate values from this values i need to get a image.
import java.io.*;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
class spe
{
public static void main(String args[])
throws IOException
{
long start = System.currentTimeMillis();
int q=0;
File file1 = new File("filename.txt");
FileWriter fw = new FileWriter(file1.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
File file= new File("2010.png");
BufferedImage image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
int[][] clr= new int[width][height];
File files= new File("2011.png");
BufferedImage images = ImageIO.read(files);
int widthe = images.getWidth(null);
int heighte = images.getHeight(null);
File file2=new File("2009.png");
BufferedImage image2=ImageIO.read(file2);
int wid=image2.getWidth(null);
int heig=image2.getHeight(null);
int[][] colo=new int[wid][heig];
int[][] clre= new int[widthe][heighte];
int smw=0;
int smh=0;
int p=0;
// bw.write("hai");
//CALUCLATING THE SMALLEST VALUE AMONG WIDTH AND HEIGHT
if(width>widthe)
{
smw =widthe;
}
else
{
smw=width;
}
if(height>heighte)
{
smh=heighte;
}
else
{
smh=height;
}
//CHECKING NUMBER OF PIXELS SIMILARITY
for(int a=0;a<smw;a++)
{
for(int b=0;b<smh;b++)
{
clre[a][b]=images.getRGB(a,b);
clr[a][b]=image.getRGB(a,b);
colo[a][b]=image2.getRGB(a,b);
if(clr[a][b]==clre[a][b] && colo[a][b]==clre[a][b])
{
p=p+1;
bw.write("\t");
bw.write(Integer.toString(a));
bw.write("\t");
bw.write(Integer.toString(b));
bw.write("\n");
System.out.println(a+"\t"+b);
}
else
q=q+1;
}
}
float w,h=0;
if(width>widthe)
{
w=width;
}
else
{
w=widthe;
}
if(height>heighte)
{
h = height;
}
else
{
h = heighte;
}
float s = (smw*smh);
//CALUCLATING PERCENTAGE
float x =(100*p)/s;
System.out.println("THE PERCENTAGE SIMILARITY IS APPROXIMATELY ="+x+"%");
long stop = System.currentTimeMillis();
System.out.println("TIME TAKEN IS ="+(stop-start));
System.out.println("NO OF PIXEL GETS VARIED:="+q);
System.out.println("NO OF PIXEL GETS MATCHED:="+p);
}
}

Data loss during conversion of video from images in Java

My video bailey.mpg from which i created .png images using xuggler method, then i read each image in byte array and append hash as delimiter and text data in this byte array and recreate image using this byte array.
Now i am reconstructing video in .avi format from this (text appended images)set of images. By getting the sets of .png images from new avi video using xuggler .I am reading each image in byte array, and i am searching delimiter in byte array of image's set, but I am unable to find hash delimiter.I think this means text data loss during creation of video.
what should i do?
Code for create images from video
package DifferentPackage;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.MediaListenerAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.xuggler.Global;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author pratibha
*/
public class VideoIntoFrames {
public static final double SECONDS_BETWEEN_FRAMES =1;
String inputFilename;
private static final String outputFilePrefix = "C:\\photo\\image_";
// The video stream index, used to ensure we display frames from one and
//only one video stream from the media container.
private static int mVideoStreamIndex = -1;
// Time of last frame write
private static long mLastPtsWrite = Global.NO_PTS;
public static final long MICRO_SECONDS_BETWEEN_FRAMES =(long)(100 * SECONDS_BETWEEN_FRAMES);
int FrameNo=0;
public VideoIntoFrames(String filepath){
inputFilename=filepath;
IMediaReader mediaReader = ToolFactory.makeReader(inputFilename);
// stipulate that we want BufferedImages created in BGR 24bit color space
mediaReader.setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR);
mediaReader.addListener(new ImageSnapListener());
// read out the contents of the media file and
// dispatch events to the attached listener
while (mediaReader.readPacket() == null) ;
}
private class ImageSnapListener extends MediaListenerAdapter {
public void onVideoPicture(IVideoPictureEvent event) {
if (event.getStreamIndex() != mVideoStreamIndex) {
// if the selected video stream id is not yet set, go ahead an
// select this lucky video stream
if (mVideoStreamIndex == -1)
mVideoStreamIndex = event.getStreamIndex();
// no need to show frames from this video stream
else
return;
}
// if uninitialized, back date mLastPtsWrite to get the very first frame
if (mLastPtsWrite == Global.NO_PTS)
mLastPtsWrite = event.getTimeStamp() - MICRO_SECONDS_BETWEEN_FRAMES;
// if it's time to write the next frame
if (event.getTimeStamp() - mLastPtsWrite >=
MICRO_SECONDS_BETWEEN_FRAMES) {
++FrameNo;
String outputFilename = dumpImageToFile(event.getImage());
// indicate file written
double seconds = ((double) event.getTimeStamp()) /
Global.DEFAULT_PTS_PER_SECOND;
System.out.printf(
"at elapsed time of %6.3f seconds wrote: %s\n",
seconds, outputFilename);
// update last write time
mLastPtsWrite += MICRO_SECONDS_BETWEEN_FRAMES;
}
}
private String dumpImageToFile(BufferedImage image) {
try {
String outputFilename = outputFilePrefix +FrameNo+ ".gif";
ImageIO.write(image, "jpg", new File(outputFilename));
return outputFilename;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public static void main(String args[]){
String path="D:/bailey.mpg";
VideoIntoFrames v=new VideoIntoFrames(path);
}
}
All images are save at c:/photo .Code for Insert Text Data in image_1.gif is
try{
String data="My Name is ";
int[] charValue=new int[data.length()];
for(int rowIndex=0;rowIndex<charValue.length;rowIndex++){
charValue[rowIndex]=data.charAt(rowIndex);
}
File videoFile = new File("C:/photo/image_1.gif");
FileInputStream videoInput = new FileInputStream(videoFile);
int VideoByte = -1;
List<Byte> bytes = new ArrayList<Byte>();
while ((VideoByte = videoInput.read()) != -1) {
bytes.add((byte) VideoByte);
}
byte[] ByteOfVideo = new byte[bytes.size()];
for (int count = 0; count < ByteOfVideo.length; count++) {
ByteOfVideo[count] = bytes.get(count);
// System.out.println(count+" of ByteOfImage "+ByteOfVideo[count]);
}
////////////////////////////////////#////////////////////////
/////now insert actual image fRames,Row and Columns
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
for (int i = 0; i < ByteOfVideo.length; i++) {
byteOut.write(ByteOfVideo[i]);
}
byte[] HashArray = "#".getBytes();
byteOut.write(HashArray);
byteOut.write(HashArray);
byteOut.write(HashArray);
byteOut.write(HashArray);
byteOut.write(HashArray);
/// String retrievedString = new String(FrameByteArray, "UTF-8");
for (int i = 0; i < charValue.length; i++) {
System.out.println(" NameArray in Bytes" + charValue[i]);
byteOut.write(charValue[i]);
}
////insert #
//////write this Video File
String FinalModifiedVideo="C:\\photo\\image_1.gif";
File ModifiedFile=new File(FinalModifiedVideo);
DataOutputStream out=new DataOutputStream(new FileOutputStream(ModifiedFile));
byteOut.writeTo(out);
out.close();
System.out.println("Process End");
}
catch(Exception e){
e.printStackTrace();
}
Code for create video from image set(images in c:/photo) folder.this create image.avi video
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Frame;
import test.*;
import ch.randelshofer.media.avi.AVIOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author Inbo
*/
public class MyVideoWriter {
static ArrayList<String> img = new ArrayList();
public static void readFiles() {
String path = "C:\\photo\\";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
int c = 0;
for (int i = 0; i <799; i++) {
img.add(path + "\\image_" + (i + 1) + ".gif");
}
// System.out.println(img);
}
public MyVideoWriter(String path) {
readFiles();
try {
AVIOutputStream AVIout = new AVIOutputStream(new File(path + ".avi"), AVIOutputStream.VideoFormat.JPG);
AVIout.setVideoCompressionQuality(1);
//AVIout.setFrameRate(10);
AVIout.setVideoDimension(352, 240);
for (int i = 0; i < img.size(); i++) {
AVIout.writeFrame(new File(img.get(i)));
}
AVIout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
String path="C:\\image";
MyVideoWriter mv = new MyVideoWriter(path);
}
}

Categories

Resources