JavaScript Practice: Duplicate an Image

Hi there, before you read my post, you can open Duke’s JavaScript Programming Environment, so you can test my codes. Link:

http://www.dukelearntoprogram.com/course1/example/index.php

The purpose is to duplicate the image of Susan into 2×2.

Original image:

rodger

Resulting image from running the program:

myImage(1)

So I wrote this:

Code1

d4

Then I realized that I could simplify it:

(1)”var p = image.getPixel(x,y)” was repeatedly written after the if, else statement, which was totally unnecessary. Instead, I can write this:

 if (x<=w-1 && y<=h-1){
 x=x; y=y;
 }
 else if (x>w-1 && y<=h-1) {
 x=x-w; y=y;
 }
 else if (x<=w-1){
 x=x; y=y-h;
 }
 else {
 x=x-w; y=y-h;
 }
 var p = image.getPixel(x,y);

(2) I can use Math. floor method.

So I revised my code and  got this:

Code2

d_simplified

Afterwards, I thought it would be better to make a function with parameters. So I got this:

Code3

d_parameter2

var image = new SimpleImage("rodger.png");
w = image.getWidth();
h = image.getHeight();
var outimage= new SimpleImage(2*w,2*h);
for (var pixel of outimage.values()){
 x = pixel.getX();
 y = pixel.getY();
 if (x<=w-1 && y<=h-1){
 var p = image.getPixel(x,y);
 }
 else if (x>w-1 && y<=h-1) {
 var p = image.getPixel((x-w),y);
 }
 else if (x<=w-1){
 var p = image.getPixel(x,(y-h));
 }
 else var p = image.getPixel((x-w),(y-h));
 pixel.setRed(p.getRed());
 pixel.setGreen(p.getGreen());
 pixel.setBlue(p.getBlue());
}
print(outimage);

Result:

myImage3

You can change the numbers 3 and 4 to other positive whole numbers to get the result you want.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s