* 2D Arrays as Images
2D arrays can be sued to represent images. The cells are filled with special values
that can be interpreted as colors when drawn to the screen.
In this example we resized an image so that it has twice the original dimensions.
Essentially, we transferred pixel values from the given small image to the corresponding
location in the big image. Since the big image has more cells than the original,
we had to copy each pixel four times (self + three adjacent) to fill the gaps.
We figured out a relationship between the location (sr,sc) in the small image and
the location (br,bc) in the big image:
br = 2*sr
bc = 2*sc
Here is the code along with test cases that show how to use:
canvas.readImage( filename )
canvas.drawImage( center-X, center-Y, 2D-array )
public class TablesApp
{
int[][] enlargeImage( int[][] smallImage )
{
int smallRows = smallImage.length;
int smallCols = smallImage[ 0 ].length;
int[][] bigImage = new int[ 2*smallRows ][ 2*smallCols ];
for ( int sr = 0 ; sr < smallRows ; sr++ )
{
for ( int sc = 0 ; sc < smallCols ; sc++ )
{
int br = 2*sr;
int bc = 2*sc;
// transfer from small image to 4 neighbors in big image
bigImage[ br ][ bc ] = smallImage[ sr ][ sc ];
bigImage[ br ][ bc + 1 ] = smallImage[ sr ][ sc ];
bigImage[ br + 1 ][ bc ] = smallImage[ sr ][ sc ];
bigImage[ br + 1 ][ bc + 1 ] = smallImage[ sr ][ sc ];
}
}
return bigImage;
}
int[][] shrinkImage( int[][] bigImage )
{
int bigRows = bigImage.length;
int bigCols = bigImage[ 0 ].length;
int[][] smallImage = new int[ bigRows / 2 ][ bigCols / 2 ];
for ( int br = 0 ; br < bigRows ; br = br + 2 )
{
for ( int bc = 0 ; bc < bigCols ; bc = bc + 2 )
{
int sr = br / 2;
int sc = bc / 2;
// transfer from big image in small image
smallImage[ sr ][ sc ] = bigImage[ br ][ bc ];
}
}
return smallImage;
}
public void run()
{
int[][] smallPuppy = canvas.readImage( "puppy.png" ); // load image as 2D array
int[][] bigPuppy = enlargeImage( smallPuppy );
int[][] smallPuppyCopy = shrinkImage( bigPuppy );
canvas.drawImage( 150, 300, smallPuppy ); // draw 2D array as image
canvas.sleep( 1 );
canvas.clear();
canvas.drawImage( 150, 300, bigPuppy ); // draw 2D array as image
canvas.sleep( 1 );
canvas.clear();
canvas.drawImage( 150, 300, smallPuppyCopy ); // draw 2D array as image
}
}