Sie sind auf Seite 1von 60

EX.

NO:

IMPLEMENTATION OF DYNAMIC MULTICASTING

DATE:

WITH CONCURRENCY CONTROL

AIM:
To implement dynamic multicasting with concurrency control using network
simulator tool.
PROCEDURE:
1. Create a tcl script called dynamic multicasting.tcl
2. Execute the script by $ ns dynamic_multicasting.tcl
3. In the script, two files are generated namely dynamic_multicasting.tr as tracefile and
dynamic_multicasting.nam as the network animator file.
CODING:
# Create scheduler
#Create an event scheduler wit multicast turned on
set ns [new Simulator -multicast on]
#$ns multicast
#Turn on Tracing
settf [open output.tr w]
$ns trace-all $tf
# Turn on nam Tracing
setfd [open mcast.nam w]
$ns namtrace-all $fd
# Create nodes
set n0 [$ns node]

set n1 [$ns node]


set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
# Create links
$ns duplex-link $n0 $n2 1.5Mb 10ms DropTail
$ns duplex-link $n1 $n2 1.5Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link $n3 $n4 1.5Mb 10ms DropTail
$ns duplex-link $n3 $n7 1.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 1.5Mb 10ms DropTail
$ns duplex-link $n4 $n6 1.5Mb 10ms DropTail
# Routing protocol: say distance vector
#Protocols: CtrMcast, DM, ST, BST
setmproto DM
setmrthandle [$ns mrtproto $mproto {}]
# Allocate group addresses
set group1 [Node allocaddr]
set group2 [Node allocaddr]

# UDP Transport agent for the traffic source

set udp0 [new Agent/UDP]


$ns attach-agent $n0 $udp0
$udp0 set dst_addr_ $group1
$udp0 set dst_port_ 0
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp0
# Transport agent for the traffic source
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
$udp1 set dst_addr_ $group2
$udp1 set dst_port_ 0
set cbr2 [new Application/Traffic/CBR]
$cbr2 attach-agent $udp1
# Create receiver
set rcvr1 [new Agent/Null]
$ns attach-agent $n5 $rcvr1
$ns at 1.0 "$n5 join-group $rcvr1 $group1"
set rcvr2 [new Agent/Null]
$ns attach-agent $n6 $rcvr2
$ns at 1.5 "$n6 join-group $rcvr2 $group1"
set rcvr3 [new Agent/Null]
$ns attach-agent $n7 $rcvr3
$ns at 2.0 "$n7 join-group $rcvr3 $group1"

set rcvr4 [new Agent/Null]


$ns attach-agent $n5 $rcvr1
$ns at 2.5 "$n5 join-group $rcvr4 $group2"
set rcvr5 [new Agent/Null]
$ns attach-agent $n6 $rcvr2
$ns at 3.0 "$n6 join-group $rcvr5 $group2"
set rcvr6 [new Agent/Null]
$ns attach-agent $n7 $rcvr3
$ns at 3.5 "$n7 join-group $rcvr6 $group2"
$ns at 4.0 "$n5 leave-group $rcvr1 $group1"
$ns at 4.5 "$n6 leave-group $rcvr2 $group1"
$ns at 5.0 "$n7 leave-group $rcvr3 $group1"
$ns at 5.5 "$n5 leave-group $rcvr4 $group2"
$ns at 6.0 "$n6 leave-group $rcvr5 $group2"
$ns at 6.5 "$n7 leave-group $rcvr6 $group2"
# Schedule events
$ns at 0.5 "$cbr1 start"
$ns at 9.5 "$cbr1 stop"
$ns at 0.5 "$cbr2 start"
$ns at 9.5 "$cbr2 stop"
#post-processing
$ns at 10.0 "finish"

proc finish {} {
global ns tf
$ns flush-trace
close $tf
execnammcast.nam&
exit 0
}
# Fornam
#Colors for packets from two mcast groups
$ns color 10 red
$ns color 11 green
$ns color 30 purple
$ns color 31 green
# Manual layout: order of the link is significant!
#$ns duplex-link-op $n0 $n1 orient right
#$ns duplex-link-op $n0 $n2 orient right-up
#$ns duplex-link-op $n0 $n3 orient right-down
# Show queue on simplex link n0->n1
#$ns duplex-link-op $n2 $n3 queuePos 0.5
# Group 0 source
$udp0 set fid_ 10
$n0 color red
$n0 label "Source 1"
# Group 1 source

$udp1 set fid_ 11


$n1 color green
$n1 label "Source 2"
$n5 label "Receiver 1"
$n5 color blue
$n6 label "Receiver 2"
$n6 color blue
$n7 label "Receiver 3"
$n7 color blue
#$n2 add-mark m0 red
#$n2 delete-mark m0"
# Animation rate
$ns set-animation-rate 3.0ms
$ns run

OUTPUT:

RESULT:
Thus the dynamic multicasting with concurrency control has been
implemented successfully.

EX NO:

IMPLEMENTATION OF D* ALGORITHM

DATE:

WITH SPATIAL DATA STRUCTURES

AIM:
To write a program to implement D* algorithm with spatial data structures.
ABOUT D* ALGORITHM:
The original D* ALGORITHM was introduced by Anthony Stentz in 1994. The name
D* comes from the term "Dynamic A*", because the algorithm behaves like A* except that
the arc costs can change as the algorithm runs. It is an incremental search algorithm.
Operation
Like Dijkstra's algorithm and A*, D* maintains a list of nodes to be evaluated, known as the
"OPEN list". Nodes are marked as having one of several states:

NEW, meaning it has never been placed on the OPEN list

OPEN, meaning it is currently on the OPEN list

CLOSED, meaning it is no longer on the OPEN list

RAISE, indicating its cost is higher than the last time it was on the OPEN list

LOWER, indicating its cost is lower than the last time it was on the OPEN list

PROCEDURE:
1.
2.
3.
4.
5.
6.

Start the program.


Include the Dstar.h header file.
In the main () method call dstar() method and input the start state.
Perform the initialize, update cell, get path and replan operation.
Display the goal state and its cost.
Stop the program.

CODING:
#include "Dstar.h"
int main() {
Dstar *dstar = new Dstar();
list mypath;
dstar->init(0,0,10,5); // set start to (0,0) and goal to (10,5)
dstar->updateCell(3,4,-1); // set cell (3,4) to be non traversable
dstar->updateCell(2,2,42.432); // set set (2,2) to have cost 42.432
dstar->replan(); // plan a path
mypath = dstar->getPath(); // retrieve path
dstar->updateStart(10,2); // move start to (10,2)
dstar->replan(); // plan a path
mypath = dstar->getPath(); // retrieve path
dstar->updateGoal(0,1); // move goal to (0,1)
dstar->replan(); // plan a path
mypath = dstar->getPath(); // retrieve path
return 0;
}

RESULT:

Thus the program to implement D* algorithm with spatial data structures is


successfully executed and verified.

EX No:

IMPLEMENTATION OF 2D TRANSFORMATION

DATE:

TRANSLATION, SCALING, ROTATION,


MIRROR REFLECTION AND SHEARING WITH
A MENU DRIVEN PROGRAM

AIM:
To implement 2D transformation: Translation, Scaling, Rotation, Mirror Reflection
and Shearing with a menu driven program.
PROCEDURE:
1. Create a java class called Transform.java
2. The operations like Translation, Scaling , Rotation, Mirror Reflection and
Shearing are performed by using the methods of AffineTransform class of the
java.awt package.
3. Embed this Transform.java with an html file called Transform.html
4. Compile the file using javac Transform.java
5. Run the applet by using appletviewer Transform.html

CODING:
import java.lang.Integer;
import java.awt.*;

import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
/*
* This applet renders a shape, selected by the user, with a paint,stroke, and rendering
method,
* also selected by the user.
*/
public class Transform extends JApplet implements ItemListener,
ActionListener {
JLabel primLabel, lineLabel, paintLabel, transLabel, strokeLabel;
TransPanel display;
static JComboBox primitive, line, paint, trans, stroke;
JButton redraw;
public static boolean no2D = false;
public void init() {
GridBagLayout layOut = new GridBagLayout();
getContentPane().setLayout(layOut);
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1.0;
c.fill = GridBagConstraints.BOTH;
primLabel = new JLabel();
primLabel.setText("Primitive");
Font newFont = getFont().deriveFont(1);
primLabel.setFont(newFont);
primLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(primLabel, c);
getContentPane().add(primLabel);

lineLabel = new JLabel();


lineLabel.setText("Lines");
lineLabel.setFont(newFont);
lineLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(lineLabel, c);
getContentPane().add(lineLabel);
paintLabel = new JLabel();
paintLabel.setText("Paints");
paintLabel.setFont(newFont);
paintLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(paintLabel, c);
getContentPane().add(paintLabel);
c.gridwidth = GridBagConstraints.RELATIVE;
transLabel = new JLabel();
transLabel.setText("Transforms");
transLabel.setFont(newFont);
transLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(transLabel, c);
getContentPane().add(transLabel);
c.gridwidth = GridBagConstraints.REMAINDER;
strokeLabel = new JLabel();
strokeLabel.setText("Rendering");
strokeLabel.setFont(newFont);
strokeLabel.setHorizontalAlignment(JLabel.CENTER);

layOut.setConstraints(strokeLabel, c);
getContentPane().add(strokeLabel);
GridBagConstraints ls = new GridBagConstraints();
ls.weightx = 1.0;

ls.fill = GridBagConstraints.BOTH;
primitive = new JComboBox( new Object []{
"rectangle",
"ellipse",
"text"});
primitive.addItemListener(this);
newFont = newFont.deriveFont(0, 14.0f);
primitive.setFont(newFont);
layOut.setConstraints(primitive, ls);
getContentPane().add(primitive);
line = new JComboBox( new Object []{
"thin",
"thick",
"dashed"});
line.addItemListener(this);
line.setFont(newFont);
layOut.setConstraints(line, ls);
getContentPane().add(line);
paint = new JComboBox( new Object[]{
"solid",
"gradient",
"polka"});
paint.addItemListener(this);
paint.setFont(newFont);
layOut.setConstraints(paint, ls);
getContentPane().add(paint);

ls.gridwidth = GridBagConstraints.RELATIVE;
trans = new JComboBox( new Object[]{
"Identity",
"rotate",

"scale",
"shear",
"translate",
"mirror reflection"});
trans.addItemListener(this);
trans.setFont(newFont);
layOut.setConstraints(trans, ls);
getContentPane().add(trans);
ls.gridwidth = GridBagConstraints.REMAINDER;
stroke = new JComboBox( new Object[]{
"Stroke",
"Fill",
"Stroke & Fill"});
stroke.addItemListener(this);
stroke.setFont(newFont);
layOut.setConstraints(stroke, ls);
getContentPane().add(stroke);
GridBagConstraints button = new GridBagConstraints();
button.gridwidth = GridBagConstraints.REMAINDER;
redraw = new JButton("Redraw");
redraw.addActionListener(this);
redraw.setFont(newFont);
layOut.setConstraints(redraw, button);
getContentPane().add(redraw);
GridBagConstraints tP = new GridBagConstraints();
tP.fill = GridBagConstraints.BOTH;
tP.weightx = 1.0;
tP.weighty = 1.0;

tP.gridwidth = GridBagConstraints.REMAINDER;
display = new TransPanel();
layOut.setConstraints(display, tP);
display.setBackground(Color.white);

getContentPane().add(display);
validate();
}
public void itemStateChanged(ItemEvent e){}
public void actionPerformed(ActionEvent e) {
display.setTrans(trans.getSelectedIndex());
display.renderShape();
}
public static void main( String[] argv ) {
if ( argv.length > 0 && argv[0].equals( "-no2d" ) ) {
Transform.no2D = true;
}
JFrame frame = new JFrame( "Transform" );
frame.addWindowListener( new WindowAdapter(){
public void windowClosing( WindowEvent e ){
System.exit( 0 );
}
});
JApplet applet = new Transform();
frame.getContentPane().add( BorderLayout.CENTER, applet );
applet.init();
frame.setSize( 550, 400 );
frame.setVisible(true);
}
}

class TransPanel extends JPanel {


AffineTransform at = new AffineTransform();
int w, h;

Shape shapes[] = new Shape[3];


BufferedImage bi;
boolean firstTime = true;
public TransPanel(){
setBackground(Color.white);
shapes[0] = new Rectangle(0, 0, 100, 100);
shapes[1] = new Ellipse2D.Double(0.0, 0.0, 100.0, 100.0);
TextLayout textTl = new TextLayout("Text", new Font("Helvetica", 1, 96), new
FontRenderContext(null, false, false));
AffineTransform textAt = new AffineTransform();
textAt.translate(0, (float)textTl.getBounds().getHeight());
shapes[2] = textTl.getOutline(textAt);
}
public void setTrans(int transIndex) {
// Sets the AffineTransform.
switch ( transIndex ) {
case 0 : at.setToIdentity();
at.translate(w/2, h/2); break;
case 1 : at.rotate(Math.toRadians(45)); break;
case 2 : at.scale(0.5, 0.5); break;
case 3 : at.shear(0.5, 0.0); break;
case 4 : at.translate(0.5, 0.5); break;
case 5 : at.scale(-1.0,1.0); break;
}
}

public void renderShape() {


repaint();
}
public void paintComponent(Graphics g) {

super.paintComponent(g);
if ( !Transform.no2D ) {
Graphics2D g2 = (Graphics2D) g;
Dimension d = getSize();
w = d.width;
h = d.height;
// Prints out the intructions.
String instruct = "Pick a primitive, line style, paint, transform,";
TextLayout thisTl = new TextLayout(instruct, new Font("Helvetica", 0, 10),
g2.getFontRenderContext());
float width = (float)thisTl.getBounds().getWidth();
float height = (float)thisTl.getBounds().getHeight();
thisTl.draw(g2, w/2-width/2, 15);
instruct = "and rendering method and click the Redraw button.";
thisTl = new TextLayout(instruct, new Font("Helvetica", 0, 10),
g2.getFontRenderContext());
width = (float)thisTl.getBounds().getWidth();
thisTl.draw(g2, w/2-width/2, height + 17);
// Initialize the transform.
if (firstTime) {
at.setToIdentity();
at.translate(w/2, h/2);
firstTime = false;
}
// Sets the Stroke.
Stroke oldStroke = g2.getStroke();

switch ( Transform.line.getSelectedIndex() ) {
case 0 : g2.setStroke(new BasicStroke(3.0f)); break;
case 1 : g2.setStroke(new BasicStroke(8.0f)); break;
case 2 : float dash[] = {10.0f};

g2.setStroke(new BasicStroke(3.0f, BasicStroke.CAP_BUTT,


BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f));
break;
}
// Sets the Paint.
Paint oldPaint = g2.getPaint();
switch ( Transform.paint.getSelectedIndex() ) {
case 0 : g2.setPaint(Color.blue);break;
case 1 : g2.setPaint(new GradientPaint(0, 0, Color.lightGray, w-250, h,
Color.blue, false));
break;
case 2 : BufferedImage buffi = new BufferedImage(15, 15,
BufferedImage.TYPE_INT_RGB);
Graphics2D buffig = buffi.createGraphics();
buffig.setColor(Color.blue);
buffig.fillRect(0, 0, 15, 15);
buffig.setColor(Color.lightGray);
buffig.translate((15/2)-(5/2), (15/2)-(5/2));
buffig.fillOval(0, 0, 7, 7);
Rectangle r = new Rectangle(0,0,25,25);
g2.setPaint(new TexturePaint(buffi, r));
break;
}
// Sets the Shape.
Shape shape = shapes[Transform.primitive.getSelectedIndex()];
Rectangle r = shape.getBounds();

// Sets the selected Shape to the center of the Canvas.


AffineTransform saveXform = g2.getTransform();
AffineTransform toCenterAt = new AffineTransform();
toCenterAt.concatenate(at);

toCenterAt.translate(-(r.width/2), -(r.height/2));
g2.transform(toCenterAt);
// Sets the rendering method.
switch ( Transform.stroke.getSelectedIndex() ) {
case 0 : g2.draw(shape); break;
case 1 : g2.fill(shape); break;
case 2 : Graphics2D tempg2 = g2;
g2.fill(shape);
g2.setColor(Color.darkGray);
g2.draw(shape);
g2.setPaint(tempg2.getPaint()); break;
}
g2.setStroke(oldStroke);
g2.setPaint(oldPaint);
g2.setTransform(saveXform);
}
}}

OUTPUT:
Rotate:

Scale:

Shear:

Translate:

Mirror Reflection:

RESULT:
Thus the 2D transformation program for Translation, Scaling, Rotation, Mirror
Reflection and Shearing with a menu driven program has been implemented
successfully.

EX NO:
DATE:

IMPLEMENT VARIOUS IMAGE COMPRESSION


ALGORITHMS.

AIM
To create a program to implement an image compression algorithm.
PROCEDURE

1. Start the program.


2. Create a class named Huffman encoder and declare the variables.
3. Create two file types namely in-file & out-file.
4. The file name, file size, compressed size and ratio are displayed finally and
traverse the tree.
5. Create a class named Huffman decoder and declare the variables.
6. Decode the values and create a priority queue; then a tree is created.
7. The compressed size and size after decompression is displayed.
8. Stop the program.

CODING
//Huffman Encoder
package Algorithms.Huffman;
import java.io.*;
import javax.swing.*;
public class HuffmanEncoder{
private static String code[],summary="";

private int totalBytes=0;


private int count=0;
private File inputFile;
private File outputFile ;
private FileOutputStream fos;
private ObjectOutputStream oos;
private BufferedOutputStream bos;
private FileInputStream fis;
private BufferedInputStream bis;
private boolean done=false;
public HuffmanEncoder(File inFile, File outFile){
inputFile=inFile;
outputFile=outFile;
encode();
}
public void encode()
{
int freq[]=new int[256];
for(int i=0;i<256;i++){
freq[i]=0;
}
//File inputFile = new File(JOptionPane.showInputDialog("Enter the input file
name"));
try{
fis = new FileInputStream(inputFile);
bis= new

BufferedInputStream(fis);

}catch(Exception eee){
System.out.println("Error 1 : "+eee);
}
try{
//System.out.println(" "+bis.available());

totalBytes=bis.available();
int mycount=0;
bis.mark(totalBytes);
while (mycount<totalBytes){
int a=bis.read();
mycount++;
freq[a]++;
}
bis.reset();
}catch(IOException eofexc){
System.out.println("Error 2: "+eofexc);
}
HuffmanNode tree = new HuffmanNode(),one,two;
PriorityQueue q = new PriorityQueue();
try{
for(int j=0;j<256;j++){
//System.out.println("\n"+byteval[j]+" "+freq[j]+
//

" prob "+probablity[j]+"int value"+toInt(byteval[j]));


if (freq[j]>0){
HuffmanNode t=new

HuffmanNode("dipu",freq[j],j,null,null,null);
q.insertM(t);
}
}
//create tree....................................
while (q.sizeQ()>1){
one=q.removeFirst();
two=q.removeFirst();
int f1=one.getFreq();
int f2=two.getFreq();
if (f1>f2){

HuffmanNode t = new HuffmanNode(null,


(f1+f2),0,two,one,null);
one.up=t;
two.up=t;
q.insertM(t);
}
else{
HuffmanNode t=new HuffmanNode(null,
(f1+f2),0,one,two,null);
one.up=t;
two.up=t;
q.insertM(t);
}
}
tree =q.removeFirst();
}catch(Exception e){
System.out.println("Priority Queue error");
}
code=new String[256];
for(int i=0;i<256;i++)
code[i]="";
traverse(tree);
Table rec=new Table(totalBytes,inputFile.getName());

for(int i=0;i<256;i++){
rec.push(freq[i]);
if(freq[i]==0)
continue;
//System.out.println(""+i+" "+code[i]+" ");
}

//System.out.println("size of table"+rec.recSize());
//*****create tree ends*****//
//System.out.println("\n total= "+totalBytes+"\n probablity="+d);
int wrote=0,csize=0;
int recordLast=0;
try{
//outputFile = new File(inputFile.getName()+".hff");
fos=new FileOutputStream(outputFile);
oos=new ObjectOutputStream(fos);
bos=new BufferedOutputStream(fos);
oos.writeObject(rec);
String outbyte="";
while (count<totalBytes){
outbyte+=code[bis.read()];
count++;
if (outbyte.length()>=8){
int k=toInt(outbyte.substring(0,8));
csize++;
bos.write(k);
outbyte=outbyte.substring(8);
}
}
while(outbyte.length()>8){
csize++;
int k=toInt(outbyte.substring(0,8));
bos.write(k);
outbyte=outbyte.substring(8);
}
if((recordLast=outbyte.length())>0){
while(outbyte.length()<8)
outbyte+=0;
bos.write(toInt(outbyte));

csize++;
}
bos.write(recordLast);
bos.close();
}
catch(Exception re){
System.out.println("Error bis writing to file");
}
float ff=(float)csize/((float)totalBytes);
System.out.println("Compression "+recordLast+" ratio "+csize+" "+
(ff*100)+" %");
summary+="File name : "+ inputFile.getName();
summary+="\n";
summary+="File size : "+totalBytes+" bytes.";
summary+="\n";
summary+="Compressed size : "+ csize+" bytes.";
summary+="\n";
summary+="Compression ratio: "+(ff*100)+" %";
summary+="\n";
done=true;
}

private void traverse(HuffmanNode n){


if (n.lchild==null&&n.rchild==null){
HuffmanNode m=n;
int arr[]=new int[20],p=0;
while (true){
if (m.up.lchild==m){
arr[p]=0;

}
else{
arr[p]=1;
}
p++;
m=m.up;
if(m.up==null)
break;
}
for(int j=p-1;j>=0;j--)
code[n.getValue()]+=arr[j];
}
if(n.lchild!=null)
traverse(n.lchild);
if(n.rchild!=null)
traverse(n.rchild);
}
private String toBinary(int b){
int arr[]=new int[8];
String s="";
for(int i=0;i<8;i++){
arr[i]=b%2;
b=b/2;
}

for(int i=7;i>=0;i--){
s+=arr[i];
}
return s;
}
private int toInt(String b){
int output=0,wg=128;

for(int i=0;i<8;i++){
output+=wg*Integer.parseInt(""+b.charAt(i));
wg/=2;
}
return output;
}
public int lengthOftask(){
return totalBytes;
}
public int getCurrent(){
return count;
}
public String getSummary(){
String temp=summary;
summary="";
return temp;
}
public boolean isDone(){
return done;
}
}

//Huffman Decoder
package Algorithms.Huffman;
import java.io.*;
import javax.swing.*;
public class HuffmanDecoder {
private int totalBytes=0,mycount=0;

private int freq[],arr=0;


private String summary="";
private File inputFile;
private Table table;
private FileInputStream in1;
private ObjectInputStream inF;
private BufferedInputStream in;
private File outputFile ;
private FileOutputStream outf;
public HuffmanDecoder(File inFile, File outFile){
inputFile = inFile;
outputFile = outFile;
decode();
}
public void decode(){
freq=new int[256];
for(int i=0;i<256;i++){
freq[i]=0;
}
// File inputFile = new File(JOptionPane.showInputDialog("Enter the input File
name"));

try
{
in1 = new FileInputStream(inputFile);
inF=new ObjectInputStream(in1);
in=new BufferedInputStream(in1);
//

int arr=0;
table=(Table)(inF.readObject());

//outputFile = new File(table.fileName());


outf=new FileOutputStream(outputFile);
summary+="File name : "+ table.fileName();
summary+="\n";
} catch(Exception exc){
System.out.println("Error creating file");
JOptionPane.showMessageDialog(null,"Error"+"\nNot a valid < hff >
format file.","Summary",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
HuffmanNode tree=new HuffmanNode(),one,two;
PriorityQueue q=new PriorityQueue();
try{
//*****creating priority queue ******//
for(int j=0;j<256;j++){
int r =table.pop();
//

System.out.println("Size of table "+r+" "+j);


if (r>0){

HuffmanNode t=new HuffmanNode("dipu",r,j,null,null,null);


q.insertM(t);
}
}

//****** create tree ******//


while (q.sizeQ()>1){
one=q.removeFirst();
two=q.removeFirst();
int f1=one.getFreq();

int f2=two.getFreq();
if (f1>f2){
HuffmanNode t=new HuffmanNode(null,
(f1+f2),0,two,one,null);
one.up=t;
two.up=t;
q.insertM(t);
}
else{
HuffmanNode t=new HuffmanNode(null,
(f1+f2),0,one,two,null);
one.up=t;
two.up=t;
q.insertM(t);
}
}
tree =q.removeFirst();
}catch(Exception exc){
System.out.println("Priority queue exception");
}
String s="";

try{
mycount=in.available();
while (totalBytes<mycount){
arr=in.read();
s+=toBinary(arr);
while (s.length()>32){
for(int a=0;a<32;a++){

int wr=getCode(tree,s.substring(0,a+1));
if(wr==-1)continue;
else{
outf.write(wr);
s=s.substring(a+1);
break;
}
}
}
totalBytes++;
}
s=s.substring(0,(s.length()-8));
s=s.substring(0,(s.length()-8+arr));
int counter;
while (s.length()>0){
if(s.length()>16)counter=16;
else counter=s.length();
for(int a=0;a<counter;a++){
int wr=getCode(tree,s.substring(0,a+1));
if(wr==-1)continue;
else{
outf.write(wr);
s=s.substring(a+1);
break;
}
}
}
outf.close();
}catch(IOException eofexc){
System.out.println("IO error");
}
summary+="Compressed size : "+ mycount+" bytes.";
summary+="\n";
summary+="Size after decompressed : "+table.originalSize()+" bytes.";

summary+="\n";
}
private int getCode(HuffmanNode node,String decode){
while (true){
if (decode.charAt(0)=='0'){
node=node.lchild;
}
else{
node=node.rchild;
}
if (node.lchild==null&&node.rchild==null){
return node.getValue();
}
if(decode.length()==1)break;
decode=decode.substring(1);
}
return -1;
}
public String toBinary(int b){
int arr[]=new int[8];
String s="";
for(int i=0;i<8;i++){
arr[i]=b%2;
b=b/2;
}

for(int i=7;i>=0;i--){
s+=arr[i];
}
return s;
}
public int toInt(String b){
int output=0,wg=128;

for(int i=0;i<8;i++){
output+=wg*Integer.parseInt(""+b.charAt(i));
wg/=2;
}
return output;
}
public int getCurrent(){
return totalBytes;
}
public int lengthOftask(){
return mycount;
}
public String getSummary(){
return summary;
}
}

OUTPUT:

RESULT:
Thus an image compression algorithm has been created and the image has been
compressed successfully.

EX NO:

PERFORMING OPERATIONS ON IMAGE

DATE:

USING ANY IMAGE EDITING SOFTWARE

AIM:
To create an image editing tool to perform various image editing options.
PROCEDURE:

1. Start the program.


2. Load the input image from the file directory.
3. Change the color of the image to gray level.
4. Adjust the RGB ratio present in the image to vary the color intensity.
5. Write a code to draw a triangle in the image.
6. Apply median filter to the loaded image to reduce the noise level.
7. Stop the program.

CODING:
package vary;
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.util.*;

import java.awt.geom.*;
public class ImageProcessing extends JFrame{
public static Vector allimages=new Vector();
public static int winNumber=0;
public static int currentWin=0;
public static int isToolsWinActive=1;
public static int isInfoWinActive=1;
public static int WhoOperationActive=1;
public static int infoX=0;
public static int infoY=0;
public static int openFrameCount = 0;
public static JTextField txtX ;
public static JTextField txtY;
public static JLabel lbtxtcurd,lbtxtwin,lbrotX,lbrotY;
public static JLabel fromx1,fromx2,fromy1,fromy2;
public static int RGBr=0xFF;
public static int RGBg=0;
public static int RGBb=0;
public ImageProcessing(String str)
{
super(str);
}
public int getRed( int p ) {
return ((p>>16)&0xFF);
}
public int getGreen( int p ) {
return ((p>>8)&0xFF);
}
public int getBlue( int p ) {
return (p & 0xff);
}
public int createRGB(int r, int g, int b){

return new Color(r, g, b).getRGB();


}
String seeColor(String c){
String temp="";
if (c.indexOf("-")!=-1 )
temp="-";
if((c.indexOf("R")>=0) || (c.indexOf("r")>=0) )
temp+="charR";
else if((c.indexOf("G")>=0) || (c.indexOf("g")>=0) )
temp+="charG";
else if((c.indexOf("B")>=0) || (c.indexOf("b")>=0) )
temp+="charB";
else {

temp="num";

}
return temp;
}
int getNumber(int c,String ch,String number){
int temp=0;
if(ch.equals("num")){
temp=Integer.parseInt(number);
}else if(ch.indexOf("charR")>=0){
temp=getRed(c);
}else if(ch.indexOf("charG")>=0){
temp=getGreen(c);

}else if(ch.indexOf("charB")>=0){
temp=getBlue(c);
}
if(ch.indexOf("-")>=0)
temp=255-temp;
return temp;
}

BufferedImage chabgeColor(BufferedImage image,String parR,String parG,String parB)


{
System.out.println("**R= "+parR+" **G= "+parG+" **B="+parB);
int w=image.getWidth(this);
int h=image.getHeight(this);
int c,red,green,blue;
String cR,cG,cB;
BufferedImage newImage=new BufferedImage(w,h,1);
cR=seeColor(parR);
cG=seeColor(parG);
cB=seeColor(parB);
System.out.println("R= "+cR+" G= "+cG+" B="+cB);
for(int y=0;y<h;y++){
for(int x=0;x<w;x++){
c=image.getRGB(x,y);
red=getNumber(c,seeColor(parR),parR);
green=getNumber(c,seeColor(parG),parG);
blue=getNumber(c,seeColor(parB),parB);
newImage.setRGB(x,y,createRGB(red,green,blue));
}
}
return newImage;
}

BufferedImage setColorToXY(BufferedImage image,int Dx,int Dy,int Dwidth,int Dhight){


int w=image.getWidth(this);
int h=image.getHeight(this);
int c,red,green,blue;
BufferedImage newImage=new BufferedImage(w,h,1);
for(int y=0;y<h;y++){
for(int x=0;x<w;x++){
c=image.getRGB(x,y);

red=getRed(c);
green=getGreen(c);
blue=getBlue(c);
if((y<=Dhight) &&(y>=Dy) && (x<=Dwidth) &&(x>=Dx) )
newImage.setRGB(x,y,createRGB(RGBr,RGBg,RGBb));
else newImage.setRGB(x,y,createRGB(red,green,blue));
}
}
return newImage;
}
BufferedImage meanFilter1(BufferedImage img){
int w = img.getWidth(null);
int h = img.getHeight(null);
BufferedImage subimage ;
BufferedImage img2 = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
int data [] = new int[9];
int red [] = new int[9];
int green[] = new int[9];
int blue [] = new int[9];
for (int y = 1; y < h - 1; y++)
for (int x = 1; x < w - 1; x++) {
subimage = img.getSubimage(x - 1, y - 1, 3, 3);
subimage.getRGB(0, 0, 3, 3, data, 0, 3);

for (int k = 0; k < 9; k++){


Color c = new Color(data[k]);
red [k] = c.getRed();
green [k] = c.getGreen();
blue [k] = c.getBlue();
}
int r = meanValue(red);
int g = meanValue(green);

int b = meanValue(blue);
Color c = new Color(r, g, b);
img2.setRGB(x, y, c.getRGB());
}
return img2;
}
BufferedImage medianFilter(BufferedImage img){
int w = img.getWidth(null);
int h = img.getHeight(null);
BufferedImage subimage ;
BufferedImage img2 = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
int data [] = new int[9];
int red [] = new int[9];
int green[] = new int[9];
int blue [] = new int[9];
for (int y = 1; y < h - 1; y++)
for (int x = 1; x < w - 1; x++) {
subimage = img.getSubimage(x - 1, y - 1, 3, 3);
subimage.getRGB(0,0,3,3,data,0,3);
for (int k=0;k<9;k++){
Color c= new Color(data[k]);
red [k] = c.getRed();
green [k] = c.getGreen();
blue [k] = c.getBlue();
}
int r = medianValue(red);
int g = medianValue(green);
int b = medianValue(blue);
Color c = new Color(r, g, b);
img2.setRGB(x, y, c.getRGB());
}
return img2;
}

int meanValue(int a[])


{
int sum = 0;
for(int i = 0; i < 9; i++)
sum += a[i];
return sum / 9;
}
int medianValue(int a[]){
int temp;
for(int i=0;i<8;i++)
for(int j=i+1;j<9;j++)
if (a[j]<a[i]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a[4];
}
BufferedImage scale(BufferedImage image1,int rx,int ry){
AffineTransform tx = new AffineTransform();
System.out.println("The Value of rx,ry is " +rx);
tx.scale(rx,ry);
AffineTransformOp op = new AffineTransformOp(tx, null);
return op.filter(image1, null);
}
}

OUTPUT
Output Screen Main Window

Output Screen Open Image

Output Screen Loaded Image

Output Screen File Menu

Output Screen Edit Menu

Output Screen Window Menu

Output Screen Change Color Before Input

Output Screen Change Color After Input R-100, G-100, B-100

RESULT:
Thus the program for implementing image editing is successfully created using Java
swing toolkit successfully.

EX.NO:
DATE:

IMPLEMENTATION OF VOIP

AIM:
To implement VOIP using both UDP and SCTP as transport layer protocols.
ABOUT VOIP:
Voice over IP (VoIP, abbreviation of voice over Internet Protocol) commonly refers
to the communication protocols, technologies, methodologies, and transmission techniques
involved in the delivery of voice communications and multimedia sessions over Internet
Protocol (IP) networks, such as the Internet. Other terms commonly associated with VoIP
are IP telephony, Internet

telephony, voice

over

broadband (VoBB), broadband

telephony, IP communications, and broadband phone. VoIP, or Voice over Internet Protocol,
is a method for taking analog audio signals, like the kind you hear when you talk on the
phone, and turning them into digital data that can be transmitted over the Internet.

PROCEDURE:
1. Create a two tcl scripts called voip_udp.tcl and voip_sctp.tcl
2. Execute the script by $ ns voip_udp.tcl
3. In the script, two files are generated namely voip.tr as tracefile and voip.nam as
the network animator file.
4. Repeat steps 2 and 3 for voip_sctp.tcl also

CODING:
Voip_udp.tcl

# start new simulation


set ns [new Simulator]
# setup tracing/nam
settr [open voip.tr w]
setnf [open voip.nam w]
$ns trace-all $tr
$ns namtrace-all $nf
# finish function, close all trace files and open up nam
proc finish {} {
global ns nftr
$ns flush-trace
close $nf
close $tr
execnamvoip.nam&
exit 0
}
### creating nodes
set node0 [$ns node]
$node0 label "Voice 1"
$node0 color red
set node1 [$ns node]
$node1 label "Voice 2"
$node1 color blue
# creating duplex-link
$ns duplex-link $node0 $node1 256Kb 50ms DropTail
$ns duplex-link-op $node0 $node1 orient right
# setup colors
$ns color 1 Yellow
$ns color 2 Green
## 2-way VoIP connection
#Create a UDP agent and attach it to node0
set udp0 [new Agent/UDP]
$ns attach-agent $node0 $udp0
# set udp0 flowid to 1
$udp0 set fid_ 1
# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]

$cbr0 set packetSize_ 128


$cbr0 set interval_ 0.020
# set traffic class to 1
$cbr0 set class_ 1
$cbr0 attach-agent $udp0
# Create a Null sink to receive UDP
set sinknode1 [new Agent/LossMonitor]
$ns attach-agent $node1 $sinknode1
# Connect the UDP traffic source to Null sink
$ns connect $udp0 $sinknode1
set udp1 [new Agent/UDP]
$ns attach-agent $node1 $udp1
$udp1 set fid_ 2
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 128
$cbr1 set interval_ 0.020
$cbr1 set class_ 2
$cbr1 attach-agent $udp1
set sinknode0 [new Agent/LossMonitor]
$ns attach-agent $node0 $sinknode0
$ns connect $udp1 $sinknode0
# end of voice simulation setup
# start up traffic
$ns at 0.1 "$cbr0 start"
$ns at 0.1 "$cbr1 start"
$ns at 10.0 "$cbr0 stop"
$ns at 10.0 "$cbr1 stop"
$ns at 10.5 "finish"
# run the simulation
$ns run

Voip_sctp.tcl
# start new simulation
set ns [new Simulator]

# setup tracing/nam
settr [open voip.tr w]
setnf [open voip.nam w]
$ns trace-all $tr
$ns namtrace-all $nf
# finish function, close all trace files and open up nam
proc finish {} {
global ns nftr
$ns flush-trace
close $nf
close $tr
execnamvoip.nam&
exit 0
}
### creating nodes
set n0 [$ns node]
$n0 label "Voice 1"
$n0 color red
set n1 [$ns node]
$n1 label "Voice 2"
$n1 color blue
# creating duplex-link
$ns duplex-link $n0 $n1 256Kb 50ms DropTail
$ns duplex-link-op $n0 $n1 orient right
# setup colors
$ns color 1 Yellow
$ns color 2 Green
## 2-way VoIP connection
#Create a SCTP agent and attach it to n0
set sctp0 [new Agent/SCTP]
$ns attach-agent $n0 $sctp0
$sctp0 set fid_ 1
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 128
$cbr0 set interval_ 0.020
# set traffic class to 1
$cbr0 set class_ 1

$cbr0 attach-agent $sctp0


# Create a Null sink to receive Data
set sinknode1 [new Agent/LossMonitor]
$ns attach-agent $n1 $sinknode1
set sctp1 [new Agent/SCTP]
$ns attach-agent $n1 $sctp1
$sctp1 set fid_ 2
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 128
$cbr1 set interval_ 0.020
$cbr1 set class_ 2
$cbr1 attach-agent $sctp1
set sinknode0 [new Agent/LossMonitor]
$ns attach-agent $n0 $sinknode0
$ns connect $sctp0 $sctp1
$ns at 0.1 "$cbr0 start"
$ns at 0.1 "$cbr1 start"
# stop up traffic
$ns at 10.0 "$cbr0 stop"
$ns at 10.0 "$cbr1 stop"
# finish simulation
$ns at 10.5 "finish"
# run the simulation
$ns run

OUTPUT:

Voip_udp

Voip_sctp

RESULT:
Thus the program for implementing VOIP had been created successfully.

Das könnte Ihnen auch gefallen