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:
Resulting image from running the program:
So I wrote this:
Code1
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
Afterwards, I thought it would be better to make a function with parameters. So I got this:
Code3
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:
You can change the numbers 3 and 4 to other positive whole numbers to get the result you want.