Sie sind auf Seite 1von 40

Experiment - 1

Aim: Write a program java to draw some shape and save it to a raw file.

Source Code:
import MMT_Lab_Tool_Lib.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.io.*;

public class SaveImageDemo extends Thread


{
ImageDrg imgDrg = new ImageDrg();

public SaveImageDemo()
{
JButton b = new JButton("Save");
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
saveImage();
}
});
imgDrg.addButton(b);

imgDrg.setVisible(true);
}

void saveImage()
{
try
{
new Thread()
{
public void run()
{
JFileChooser fc = new JFileChooser();
int rv = fc.showOpenDialog(imgDrg);

BufferedImage img = (BufferedImage)imgDrg.getImage();


Raster r = img.getRaster();
int[] pixValue = new int[4];

int w = img.getWidth();
int h = img.getHeight();
int i=1;
try
{
FileOutputStream fout = new FileOutputStream(fc.getSelectedFile());
for(int x =0; x<w; ++x)
{
for(int y =0; y<h; ++y)
{
imgDrg.setProgress(i++);
r.getPixel(x,y,pixValue);
fout.write(intToByte(pixValue));
}
}
}
catch(Exception ex){}
imgDrg.setProgress(0);
}.start();
}
catch(Exception ex){}
}

byte[] intToByte(int[] iArr)


{
byte[] bArr = new byte[iArr.length];
for(int i=0;i<iArr.length; ++i)
bArr[i] = (byte)iArr[i];
return bArr;
}

public static void main(String[] arg)


{
new SaveImageDemo();
}
}
Output:
Experiment – 2

Aim: Write a program java to draw shapes from saved file in previous experiment.

Source Code:
import MMT_Lab_Tool_Lib.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.io.*;

public class LoadImageDemo


{
ImageDrg imgDrg = new ImageDrg();

public LoadImageDemo()
{
JButton b = new JButton("Load Image");

b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
loadImage();
}
});

imgDrg.addButton(b);

imgDrg.setVisible(true);
}

void loadImage()
{
try
{
new Thread()
{
public void run()
{
JFileChooser fc = new JFileChooser();
int rv = fc.showOpenDialog(imgDrg);

if(rv == fc.APPROVE_OPTION);
{
BufferedImage img = (BufferedImage)imgDrg.getImage();
WritableRaster r = img.getRaster();

byte[] pixValue = new byte[4];


int w = img.getWidth();
int h = img.getHeight();

int i=1;

try
{
FileInputStream fin = new
FileInputStream(fc.getSelectedFile());

for(int x =0; x<w; ++x)


{
for(int y =0; y<h; ++y)
{
fin.read(pixValue);
r.setPixel(x,y,byteToInt(pixValue));
imgDrg.setProgress(i++);
}
}

}
catch(Exception ex){}
}

imgDrg.repaint();
imgDrg.setProgress(0);

}
}.start();
}
catch(Exception ex){}
}

int[] byteToInt(byte[] bArr)


{
int[] iArr = new int[bArr.length];
for(int i=0;i<iArr.length; ++i)
iArr[i] = bArr[i];
return iArr;
}

public static void main(String[] arg)


{
new LoadImageDemo();
}
}
Output:
Experiment – 3
Aim: Write a program in java to read a bmp file and display header and other information
except pixel data.
Source Code:

import java.io.*;
import javax.swing.*;

public class BMPInfo


{
File bmpFile = null;
FileInputStream fin = null;

//===== header field ========


short fileType = 0;
short reserved1 = 0;
short reserved2 = 0;
int bitmapOffset = 0;
int fileSize = 0;
int dibHeaderSize = 0;
int width = 0;
int height = 0;
short planes = 0;
short bitsPerPixel = 0;
int compression = 0;
int sizeOfBitmap = 0;
int horzResolution = 0;
int vertResolution = 0;
int colorsUsed = 0;
int colorsImportant = 0;

public BMPInfo(File file) throws Exception


{
bmpFile = file;
fin = new FileInputStream(file);
readHeader();
getBitmapHeader();
}
void readHeader() throws Exception
{
fileType = readShort();
if (fileType != 0x4d42) throw new Exception("Not a BMP file");
fileSize = readInt();
reserved1 = readShort();
reserved2 = readShort();
bitmapOffset = readInt();
}
void getBitmapHeader() throws Exception
{
dibHeaderSize = readInt();
width = readInt();
height = readInt();
planes = readShort();
bitsPerPixel = readShort();
compression = readInt();
sizeOfBitmap = readInt();
horzResolution = readInt();
vertResolution = readInt();
colorsUsed = readInt();
colorsImportant = readInt();
}
public String toString()
{
StringBuffer buffer = new StringBuffer();

buffer.append("File Type : " + fileType);


buffer.append("\nFile Size : " + fileSize);
buffer.append("\nImage Offset : " + bitmapOffset);
buffer.append("\nDIB Header Size : " + dibHeaderSize);
buffer.append("\nImage Width : " + width);
buffer.append("\nImage Height : " + height);
buffer.append("\nNo Of Color Plane : " + planes);
buffer.append("\nBits Per Pixel : " + bitsPerPixel);
buffer.append("\nCompression Type : " + compression);
buffer.append("\nBitmap size : " + sizeOfBitmap);
buffer.append("\nHorizontal Resolution : " + horzResolution);
buffer.append("\nVertical Resolution : " + vertResolution);
buffer.append("\nNumber Of Colors : " + colorsUsed);
buffer.append("\nNumber Of Important Colors : " + colorsImportant);

return buffer.toString();
}

int readInt() throws IOException


{
int b1 = fin.read();
int b2 = fin.read();
int b3 = fin.read();
int b4 = fin.read();

return ((b4 << 24) + (b3 << 16) + (b2 << 8) + (b1 << 0));
}

short readShort() throws IOException


{
int b1 = fin.read();
int b2 = fin.read();

return (short) ((b2 << 8) + b1);


}
public static void main(String[] arg)
{
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
if(f.isDirectory() || f.getName().toLowerCase().endsWith(".bmp"))
return true;
return false;
}
public String getDescription()
{
return "BMP Image Files";
}
});
if(fc.showOpenDialog(null) == fc.APPROVE_OPTION);
{
try
{
BMPInfo info = new BMPInfo(fc.getSelectedFile());
JOptionPane.showOptionDialog(null,info.toString(),"BMP Header
Information",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,null,null);
}
catch(Exception ex) {
JOptionPane.showMessageDialog(null,"Invalid file");
}
}
}
}

Output:
File Name : bee.bmp
File Type : 19778
File Size : 178578
Image Offset : 1078
DIB Header Size : 40
Image Width : 500
Image Height : 355
No Of Color Plane : 1
Bits Per Pixel : 8
Compression Type : 0
Bitmap size : 177500
Horizontal Resolution : 0
Vertical Resolution : 0
Number Of Colors : 256
Number Of Important Colors : 256
Experiment – 4
Aim: Write a program in java to read a bmp file and display the image.
Source:
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.*;

public class DisplayBMP


{
public static void main(String[] arg)
{
JFileChooser fc = new JFileChooser();

fc.setFileFilter(new javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
if(f.isDirectory() || f.getName().toLowerCase().endsWith(".bmp"))
return true;
return false;
}

public String getDescription()


{
return "BMP Image Files";
}
});

if(fc.showOpenDialog(null) == fc.APPROVE_OPTION);
{
try
{
ImageIcon img = new ImageIcon(ImageIO.read(fc.getSelectedFile()));
JOptionPane.showOptionDialog(null,new
JLabel(img),fc.getSelectedFile().getName(),JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,
null,null,null);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Invalid file");
}
}
}

}
Output:
Experiment – 5
Aim: Write a program in java to read an mp3 (or any audio) file and display its header
information.
Source Code:
import java.io.*;

public class MP3Header


{
private final int HEADER_SIZE = 4;
private final int NUM_BYTES = 4;
private final int NUM_BITS = 8;

private final int MPEG_V_25 = 0;


private final int MPEG_V_2 = 2;
private final int MPEG_V_1 = 3;
private final int MPEG_L_3 = 1;
private final int MPEG_L_2 = 2;
private final int MPEG_L_1 = 3;

private File mp3File = null;


private int version;
private int layer;
private int bitRate;
private int sampleRate;
private int channelMode;
private boolean copyrighted;

private final int[][] bitrateTable = { { -1, -1, -1, -1, -1 },


{ 32, 32, 32, 32, 8 },
{ 64, 48, 40, 48, 16 },
{ 96, 56, 48, 56, 24 },
{ 128, 64, 56, 64, 32 },
{ 160, 80, 64, 80, 40 },
{ 192, 96, 80, 96, 48 },
{ 224, 112, 96, 112, 56 },
{ 256, 128, 112, 128, 64 },
{ 288, 160, 128, 144, 80 },
{ 320, 192, 160, 160, 96 },
{ 352, 224, 192, 176, 112 },
{ 384, 256, 224, 192, 128 },
{ 416, 320, 256, 224, 144 },
{ 448, 384, 320, 256, 160 },
{ -1, -1, -1, -1, -1 }
};
private final int[][] sampleTable = { { 44100, 22050, 11025 },
{ 48000, 24000, 12000 },
{ 32000, 16000, 8000 },
{ -1, -1, -1 }
};

private final String[] channelLabels = { "Stereo", "Joint Stereo (STEREO)","Dual Channel (STEREO)","Single
Channel (MONO)" };
private final String[] versionLabels = {"MPEG Version 2.5",null,"MPEG Version 2.0","MPEG Version 1.0"};
private final String[] layerLabels = { null, "3", "2","1" };

public MP3Header(File f) throws Exception


{
mp3File = f;
readHeader(findHeaderLocation());
}

private void readHeader(long location )throws Exception


{
RandomAccessFile raf = new RandomAccessFile(mp3File, "r" );
byte[] head = new byte[HEADER_SIZE];
raf.seek( location );

if( raf.read( head ) != HEADER_SIZE ) throw new Exception("Error reading MP3 frame header.");

version = convertToDecimal( head[1], 3, 4 );


layer = convertToDecimal( head[1], 1, 2 );
findBitRate( convertToDecimal( head[2], 4, 7 ) );
findSampleRate( convertToDecimal( head[2], 2, 3 ) );
channelMode = convertToDecimal( head[3], 6, 7 );
copyrighted = bitSet( head[3], 3 );
}

private void findBitRate( int bitrateIndex )


{
int ind = -1;

if( version == MPEG_V_1 )


{
if( layer == MPEG_L_1 )
ind = 0;
else if( layer == MPEG_L_2 )
ind = 1;
else if( layer == MPEG_L_3 )
ind = 2;
}
else if( (version == MPEG_V_2) || (version == MPEG_V_25) )
{
if( layer == MPEG_L_1 )
ind = 3;
else if( (layer == MPEG_L_2) || (layer == MPEG_L_3) )
ind = 4;
}

if( (ind != -1) && (bitrateIndex >= 0) && (bitrateIndex <= 15) )
bitRate = bitrateTable[bitrateIndex][ind];
}

private void findSampleRate( int sampleIndex )


{
int ind = -1;

switch( version )
{
case MPEG_V_1:
ind = 0;
break;
case MPEG_V_2:
ind = 1;
break;
case MPEG_V_25:
ind = 2;
}

if( (ind != -1) && (sampleIndex >= 0) && (sampleIndex <= 3) )


sampleRate = sampleTable[sampleIndex][ind];
}

public String toString()


{
StringBuffer buffer = new StringBuffer();
buffer.append("File Name : " + mp3File.getName());
buffer.append("\nVersion : " + versionLabels[version]);
buffer.append("\nLayer : " + layerLabels[layer]);
buffer.append("\nSample Rate : " + sampleRate + "Hz");
buffer.append("\nChannel Mode : " + channelLabels[channelMode]);

if(copyrighted)
buffer.append("\nCopywrited : Yes");
else
buffer.append("\nCopywrited : No");

return buffer.toString();
}

private long findHeaderLocation()throws Exception


{
RandomAccessFile raf = new RandomAccessFile(mp3File, "r" );
byte test;
long loc = -1;
raf.seek(0);

while( loc == -1 )
{
test = raf.readByte();
if(matchPattern( test, "11111111" ) )
{
test = raf.readByte();

if(matchPattern( test, "111xxxxx" ) )


{
loc = raf.getFilePointer() - 2;
}
}
}
return loc;
}

public boolean matchPattern( byte b, String pattern )


{
boolean retval = true;

for( int i = 0; (i < NUM_BITS) && (i < pattern.length()) && retval; i++ )
{

if(pattern.charAt(i) == '1' )
{
retval = retval && bitSet( b, NUM_BITS - i - 1 );
}
else if( pattern.charAt(i) == '0' )
{
retval = retval && !bitSet( b, NUM_BITS - i - 1 );
}
}

return retval;
}

public boolean bitSet( byte b, int pos )


{
boolean retval = false;

if( (pos >= 0) && (pos < NUM_BITS) )


{
retval = ((b & (byte)(1 << pos)) != 0);
}

return retval;
}

public int convertToDecimal( byte b, int start, int end )


{
byte ret = 0;
int bCount = 0;
int s = start;
int e = end;

if( (start < 0) || (start >= NUM_BITS) )


{
s = 0;
}

if( (end < 0) || (end >= NUM_BITS) )


{
e = NUM_BITS - 1;
}

if( start > end )


{
s = end;
e = start;
}

for( int i = s; i <= e; i++ )


{
if( bitSet( b, i ) )
ret = setBit( ret, bCount );

bCount++;
}

return ret;
}

public byte setBit( byte b, int location )


{
byte ret = 0;

if( (location >= 0) && (location < NUM_BITS) )


ret = (byte)(b | (byte)(1 << location));

return ret;
}

public static void main(String[] arg) throws Exception


{
javax.swing.JFileChooser fc = new javax.swing.JFileChooser();
fc.setFileFilter(new javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
if(f.isDirectory() || f.getName().toLowerCase().endsWith(".mp3"))
return true;

return false;
}
public String getDescription()
{
return "MPEG Files";
}
});
int rv = fc.showOpenDialog(null);
if(rv == fc.APPROVE_OPTION);
{
try
{
MP3Header info = new MP3Header(fc.getSelectedFile());
javax.swing.JOptionPane.showOptionDialog(null,info.toString(),"MP3 Header
Information",javax.swing.JOptionPane.DEFAULT_OPTION,javax.swing.JOptionPane.INFORMATION_MESSAGE,null,n
ull,null);
}
catch(Exception ex)
{
javax.swing.JOptionPane.showMessageDialog(null,"Invalid file");
}
}
}
}

Output:

1) File Name : Masti ki pathshala.mp3


Version : MPEG Version 1.0
Layer : 3
Sample Rate : 44100Hz
Channel Mode : Joint Stereo (STEREO)
Copywrited : No

2) File Name : Kid_Story.mpg


Version : MPEG Version 2.5
Layer : null
Sample Rate : 11025Hz
Channel Mode : Single Channel (MONO)
Copywrited : No
Experiment – 6
Aim: Write a program in java to compress a given text file.
Source Code:
import java.io.*;
import java.util.Observable;
import java.util.zip.*;

public class MyCodec extends Observable


{
public void compress(String src, String dest) throws IOException
{
File f = new File(src);
long size = f.length();
long count = 1;
FileInputStream in = new FileInputStream(f);
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(dest));
int c = 0;
while ((c = in.read()) != -1)
{
out.write(c);
setChanged();
notifyObservers((int)((double)count++/size * 100));
}
in.close();
out.close();
}
public static void main(String[] arg) throws Exception
{
if(arg.length == 3)
{
MyCodec c = new MyCodec();
if(arg[0].toLowerCase().equals("-c"))
{
c.compress(arg[1], arg[2]);
}
}
else
System.out.println("Use\n…For compressing file : MyCodec -c < src file> <dest file>");
}
}

Output:
C :\> java –c abc.java abc.gz
File Compressed….
Experiment -7
Aim: Write a program in java to decompress the given file.
Source:
import java.io.*;
import java.util.Observable;
import java.util.zip.*;

public class MyCodec extends Observable


{
public void decompress(String src, String dest) throws IOException
{
File f = new File(src);
long size = f.length();
long count = 1;
GZIPInputStream in = new GZIPInputStream(new FileInputStream(src));
FileOutputStream out = new FileOutputStream(dest);
int c = 0;
while ((c = in.read()) != -1)
{
out.write(c);
setChanged();
notifyObservers(=(int)((double)count++/size * 100));
}
in.close();
out.close();
}
public static void main(String[] arg) throws Exception
{
if(arg.length == 3)
{
MyCodec c = new MyCodec();
if(arg[0].toLowerCase().equals("-d"))
{
c.decompress(arg[1], arg[2]);
}
}
if(arg.length != 3)
{
System.out.println("Use\n..............");
System.out.println("use…\nFor decompressing file : MyCodec -d <src file> <dest file>");
}
}
}

Output:
C :\> java –d abc.gz abc.java
File Decompressed….

Experiment – 8

Aim: Create a GUI Tool to perform all the operations performed in previous experiments
under a single interface form.

Source Code:
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.io.*;
import java.util.*;

public class MasterFrame extends JFrame implements ActionListener


{
JDesktopPane jdp = null;

String[] options = {"Drawing","BMP File Header","File Codec"};

public MasterFrame()
{
super("MultiMedia Tool");
setExtendedState(MAXIMIZED_BOTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,400);

setUp();
setVisible(true);

addOptionFrame();
}

void setUp()
{
jdp = new JDesktopPane();
add(jdp,BorderLayout.CENTER);
}
void addOptionFrame()
{
JToolBar jtb = new JToolBar();
add(jtb,BorderLayout.NORTH);

for(String s : options)
{
JButton b = new JButton(s);
b.addActionListener(this);
b.setActionCommand(s);
jtb.add(b);
}
}

public void actionPerformed(ActionEvent ae)


{
String cmd = ae.getActionCommand();

if(cmd.equals("Drawing"))
{
jdp.add(new DrgTool());
}
else if(cmd.equals("BMP File Header"))
{
jdp.add(new BMPInfoFrame());
}
else if(cmd.equals("File Codec"))
{
jdp.add(new CodecFrame());
}
}

public static void main(String[] arg)


{
new MasterFrame();
}

class BMPInfoFrame extends JInternalFrame


{
JTextArea infoBox = new JTextArea();

public BMPInfoFrame()
{
super("BMP Header",true,true,true,true);
setSize(250,300);
setLayout(new BorderLayout());

JButton ld = new JButton("Choose BMP File");


ld.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
if(f.isDirectory() ||
f.getName().toLowerCase().endsWith(".bmp"))
return true;

return false;
}

public String getDescription()


{
return "BMP Image Files";
}
});

if(fc.showOpenDialog(null) == fc.APPROVE_OPTION);
{
try
{
infoBox.setText(new
BMPInfo(fc.getSelectedFile()).toString());
}
catch(Exception ex)
{
infoBox.setText("Invalid file...");
}
}

}
});
add(ld,BorderLayout.NORTH);

add(new JScrollPane(infoBox),BorderLayout.CENTER);

setVisible(true);
}
}

class CodecFrame extends JInternalFrame implements ActionListener,Observer


{
JTextArea srcBox = new JTextArea(5,5);
JProgressBar jpb = new JProgressBar();
JLabel infoLabel = new JLabel();

MyCodec c = new MyCodec();

File srcFile = null;


String[] cmd = {"Compress","Decompress","Save"};

boolean lock = false;

public CodecFrame()
{
super("BMP Header",true,true,true,true);
setSize(600,400);
setLayout(new BorderLayout());

add(new JScrollPane(srcBox),BorderLayout.CENTER);

JToolBar tb = new JToolBar();


add(tb,BorderLayout.NORTH);

for(String s : cmd)
{
JButton ld = new JButton(s);
tb.add(ld);
ld.setActionCommand(s);
ld.addActionListener(this);
}

tb = new JToolBar();
add(tb,BorderLayout.SOUTH);

jpb.setMaximum(100);
jpb.setStringPainted(true);
jpb.setVisible(false);
tb.add(infoLabel);
tb.add(jpb);

setVisible(true);

c.addObserver(this);
}

public void setProgress(int val)


{
if(val == 0 || val == 100)
jpb.setVisible(false);
else if(val == 1)
jpb.setVisible(true);

jpb.setValue(val);
}

public void actionPerformed(ActionEvent ae)


{
if(lock)return;
String cmd = ae.getActionCommand();

if(cmd.equals("Compress"))
{
try
{
lock = true;

new Thread()
{

public void run()


{
try
{
infoLabel.setText("Loading File...");
loadSrcFile();

File f = new File("codec.tmp");


f.createNewFile();

infoLabel.setText("Compressing File...");
c.compress(srcFile.getPath(),f.getName());

infoLabel.setText("");
}
catch(Exception ex){ex.printStackTrace();}

lock = false;
}
}.start();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
else if(cmd.equals("Decompress"))
{
try
{
lock = true;

new Thread()
{

public void run()


{
try
{
infoLabel.setText("Loading File...");
loadSrcFile();

File f = new File("codec.tmp");


f.createNewFile();

infoLabel.setText("Decompressing File...");
c.decompress(srcFile.getPath(),f.getName());

infoLabel.setText("");
}
catch(Exception ex){ex.printStackTrace();}

lock = false;
}
}.start();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
else if(cmd.equals("Save"))
{
try
{
lock = true;
infoLabel.setText("Saving File...");

try
{
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Choose File");

int rv = fc.showSaveDialog(null);

if(rv == fc.APPROVE_OPTION);
{
srcFile = fc.getSelectedFile();
srcBox.setText("");

new Thread()
{
public void run()
{
try
{
FileInputStream fin = new
FileInputStream("codec.tmp");
FileOutputStream fout = new
FileOutputStream(srcFile);
int c = 0;
long count = 1, size = new
File("codec.tmp").length();

while((c = fin.read()) != -1)


{
fout.write(c);

srcBox.append(String.valueOf((char)c));

setProgress((int)
((double)count/size * 100));
++count;
}

fin.close();
fout.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}

lock = false;
infoLabel.setText("");
}
}.start();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

public void update(Observable o, Object arg)


{
setProgress(Integer.valueOf(arg.toString()));
}

void loadSrcFile()
{
try
{
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Choose Source File");

int rv = fc.showOpenDialog(null);

if(rv == fc.APPROVE_OPTION);
{
srcFile = fc.getSelectedFile();

srcBox.setText("");

FileInputStream f = new FileInputStream(srcFile);

int c = 0;
long count = 1, size = srcFile.length();

while((c = f.read()) != -1)


{
srcBox.append(String.valueOf((char)c));

setProgress((int)((double)count/size * 100));
++count;
}

f.close();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}

}
}
}

class DrgTool extends JInternalFrame implements ActionListener,ChangeListener


{
MyCanvas canvas = null;
JToolBar tb = null;
JSpinner sp = null;
JMenuBar jb = null;
JProgressBar jpb = null;

public DrgTool()
{
super("Drawing",true,true,true,true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(400,400);
setUp();
setVisible(true);
}

void setUp()
{
jpb = new JProgressBar();
jpb.setStringPainted(true);
jpb.setVisible(false);
add(jpb,BorderLayout.SOUTH);

canvas = new MyCanvas(this);


add(new JScrollPane(canvas),BorderLayout.CENTER);

jb = new JMenuBar();

JMenu m = null;
JMenuItem mit = null;

m = new JMenu("Home");
jb.add(m);

mit = new JMenuItem("New");


mit.addActionListener(this);
mit.setActionCommand("New");
m.add(mit);

m.addSeparator();

mit = new JMenuItem("Open Raw File");


mit.addActionListener(this);
mit.setActionCommand("OPEN_RAW");
m.add(mit);

mit = new JMenuItem("Open BMP File");


mit.addActionListener(this);
mit.setActionCommand("OPEN_BMP");
m.add(mit);

m.addSeparator();

mit = new JMenuItem("Save Raw File");


mit.addActionListener(this);
mit.setActionCommand("SAVE_RAW");
m.add(mit);

mit = new JMenuItem("Save BMP File");


mit.addActionListener(this);
mit.setActionCommand("SAVE_BMP");
m.add(mit);

m.addSeparator();
mit = new JMenuItem("Exit");
mit.addActionListener(this);
mit.setActionCommand("EXIT");
m.add(mit);

m = new JMenu("Drawing");
jb.add(m);

mit = new JMenuItem("Brush Color ");


mit.addActionListener(this);
mit.setActionCommand("BRUSH_COLOR");
m.add(mit);

sp = new JSpinner();
sp.setValue(2);
sp.addChangeListener(this);
mit = new JMenuItem(" ");
mit.setLayout(new GridLayout(1,2));
mit.add(new JLabel(" Brush Size"));
mit.add(sp);
m.add(mit);

setJMenuBar(jb);

public void setMaxVal(int mv)


{
jpb.setMaximum(mv);
}

public void setProgress(int v)


{
jpb.setValue(v);

if(v == 0)
jpb.setVisible(false);
else if(v == 1)
jpb.setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{
String cmd = ae.getActionCommand();

if(cmd.equals("BRUSH_COLOR"))
{
Color c = JColorChooser.showDialog(this,"",null);
if(c != null)
canvas.setBrushColor(c);
}
else if(cmd.equals("New"))
{
canvas.newImage();
}
else if(cmd.equals("OPEN_RAW"))
{
canvas.loadRawImage();
}
else if(cmd.equals("SAVE_RAW"))
{
canvas.saveRawImage();
}

else if(cmd.equals("OPEN_BMP"))
{
canvas.loadBMPImage();
}
else if(cmd.equals("SAVE_BMP"))
{
canvas.saveBMPImage();
}
else if(cmd.equals("EXIT"))
{
System.exit(0);
}
}

public void stateChanged(ChangeEvent ce)


{
int i = Integer.parseInt(sp.getValue().toString());
if(i == 0)
{
sp.setValue(1);
i++;
}

canvas.setBrushSize(i);
}

public static void main(String[] arg)


{
new DrgTool();
}
}

class MyCanvas extends JPanel implements MouseListener,MouseMotionListener


{
DrgTool baseFrame = null;

int brushSize = 1;
Color brushColor = Color.black;

BufferedImage image = null;


WritableRaster raster = null;
Graphics2D g = null;

Point lastPoint = null;

boolean drawFlag = false;

int imgXpos = 0;
int imgYpos = 0;

public MyCanvas(DrgTool dt)


{
super();
setBackground(Color.white);

baseFrame = dt;

newImage();

addMouseListener(this);
addMouseMotionListener(this);

setBrushColor(Color.black);
setBrushSize(2);
}

public void paint(Graphics g)


{
super.paint(g);

if(image != null)
{
imgXpos = (getWidth() - image.getWidth())/2;
imgYpos = (getHeight() - image.getHeight())/2;
g.drawImage(image,imgXpos,imgYpos,null);
}
}

public void mousePressed(MouseEvent me)


{
if(me.getButton() == 1)
{
if(me.getX() >= imgXpos && me.getY() >= imgYpos)
{
drawFlag = true;
lastPoint = new Point(me.getX()-imgXpos, me.getY() - imgYpos);
}
}
}

public void mouseReleased(MouseEvent me)


{
drawFlag = false;
}

public void mouseDragged(MouseEvent me)


{
if(drawFlag)
{
Point p = new Point(me.getX()-imgXpos, me.getY() - imgYpos);
g.draw(new Line2D.Double(lastPoint,p));
lastPoint = p;
repaint();
}
}

public void mouseMoved(MouseEvent me){}


public void mouseEntered(MouseEvent me){}
public void mouseClicked(MouseEvent me){}
public void mouseExited(MouseEvent me){}

public void newImage()


{
newImage(800,600);
}

public void newImage(int w,int h)


{
image = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
raster = image.getRaster();
g = (Graphics2D)image.getGraphics();

g.setColor(Color.white);
g.fillRect(0,0,799,599);
g.setColor(Color.black);
g.drawRect(0,0,799,599);

baseFrame.setMaxVal(w*h);

repaint();
}

public void setImage(BufferedImage img)


{
image = img;
raster = image.getRaster();
g = (Graphics2D)image.getGraphics();
g.setColor(Color.black);
int w = img.getWidth();
int h = img.getHeight();

g.drawRect(0,0,w-1,h-1);

baseFrame.setMaxVal(w*h);

repaint();
}

public void setBrushSize(int s)


{
brushSize = s;
g.setStroke(new BasicStroke(s));
}

public void setBrushColor(Color c)


{
brushColor = c;
g.setColor(c);
}

public Image getImage()


{
return image;
}

public void loadRawImage()


{
try
{
new Thread()
{
public void run()
{
JFileChooser fc = new JFileChooser();
int rv = fc.showOpenDialog(baseFrame);

if(rv == fc.APPROVE_OPTION);
{
int[] pixValue = new int[4];

int i=1;

try
{
FileInputStream fin = new
FileInputStream(fc.getSelectedFile());

int w = readInt(fin);
int h = readInt(fin);
newImage(w,h);

for(int x =0; x<w; ++x)


{
for(int y =0; y<h; ++y)
{
pixValue[0] = fin.read();
pixValue[1] = fin.read();
pixValue[2] = fin.read();
pixValue[3] = fin.read();

raster.setPixel(x,y,pixValue);

baseFrame.setProgress(i++);
}
}

fin.close();
}
catch(Exception ex){}
}

baseFrame.repaint();
baseFrame.setProgress(0);

}
}.start();
}
catch(Exception ex){}
}

public void saveRawImage()


{
try
{
new Thread()
{
public void run()
{
JFileChooser fc = new JFileChooser();
int rv = fc.showSaveDialog(baseFrame);

if(rv == fc.APPROVE_OPTION);
{
int[] pixValue = new int[4];

int w = image.getWidth();
int h = image.getHeight();

int i=1;
try
{
FileOutputStream fout = new
FileOutputStream(fc.getSelectedFile());

writeInt(fout,w);
writeInt(fout,h);

for(int x =0; x<w; ++x)


{
for(int y =0; y<h; ++y)
{
baseFrame.setProgress(i++);
raster.getPixel(x,y,pixValue);

fout.write(pixValue[0]);
fout.write(pixValue[1]);
fout.write(pixValue[2]);
fout.write(pixValue[3]);
}
}

}
catch(Exception ex){}
}
baseFrame.setProgress(0);

JOptionPane.showMessageDialog(baseFrame,"File Saved","Raw
Image",JOptionPane.INFORMATION_MESSAGE);
}
}.start();
}
catch(Exception ex){}
}

public void loadBMPImage()


{
try
{
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
if(f.isDirectory() || f.getName().toLowerCase().endsWith(".bmp"))
return true;
return false;
}

public String getDescription()


{
return "BMP Image Files";
}
});

int rv = fc.showOpenDialog(baseFrame);
if(rv == fc.APPROVE_OPTION);
{
setImage(ImageIO.read(fc.getSelectedFile()));
baseFrame.repaint();
}
}
catch(Exception ex){}
}

public void saveBMPImage()


{
try
{
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
if(f.isDirectory() || f.getName().toLowerCase().endsWith(".bmp"))
return true;
return false;
}

public String getDescription()


{
return "BMP Image Files";
}
});

int rv = fc.showSaveDialog(baseFrame);

if(rv == fc.APPROVE_OPTION);
{
File f = fc.getSelectedFile();

String ext = "";

if(!f.getName().toLowerCase().endsWith(".bmp"))
{
ext = ".bmp";
}
if(!f.exists())
f.createNewFile();

ImageIO.write(image,"bmp",f);
JOptionPane.showMessageDialog(baseFrame,"File Saved","Save
BMP",JOptionPane.INFORMATION_MESSAGE);
}
}
catch(Exception ex){}
}
int readInt(FileInputStream fin) throws IOException
{
int b1 = fin.read();
int b2 = fin.read();
return (b2 << 8) + (b1 << 0);
}

void writeInt(FileOutputStream fout, int val) throws IOException


{
fout.write((byte)val);
fout.write((byte)(val>>8));
}
}

Output:
Experiment – 9

Aim: Study about Flash.


Experiment – 10

Aim: Study about Dreamweaver.


Experiment – 11

Aim: Design a poster using Photoshop.

Das könnte Ihnen auch gefallen