CS 145 Lecture 23 – Images Cont’d

Dear students,

I believe the ideas of computer science are best illustrated by manipulating digital media. To me, digital media presents a perfect context: it is one you are familiar with, and it is one that has real-world relevance. I’m sorry if you were hoping to work more with text and numbers. For those of you who can’t stand digital media, let’s do a group-coding exercise with text and numbers, one that came from a programming contest this past Saturday and one that is a stereotypical interview question.

Write a method blugold that accepts three numbers: a, b, and n. It prints out all numbers from 1 to n, with the following exceptions: 1) if the number is a multiple of a, print "blu" instead, 2) if the number is a multiple of b, print "gold", and 3) if the number is multiple of both a and b, print "blugold".

Now we generate some more images! Let’s write programs that…

  • draw a line between two points
  • flip an image vertically
  • display two images in split screen
  • bounce a ball

See you next class!

Sincerely,

P.S. Here’s the code we wrote together…

Blugold.java

package lecture1102;

public class Blugold {
  public static void main(String[] args) {
    blugold(3, 5, 20);
  }

  public static void blugold(int a, int b, int n) {

    for (int i = 1; i <= n; i++) {
      if (0 == i % a && 0 == i % b) {
        System.out.println("BLUGOLD!");
      } else if (0 == i % a) {
        System.out.println("Blu");
      } else if (0 == i % b) {
        System.out.println("Gold");
      } else {
        System.out.println(i);
      }
    }
// System.out.println("Go Chrrrrrriis :)))))))))))))))))");
  }
}

Splitsville.java

package lecture1102;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Splitsville {
  public static void main(String[] args) throws IOException {
    BufferedImage good = ImageIO.read(new File("/Users/johnch/Desktop/harvey_dent.jpg"));
    BufferedImage evil = ImageIO.read(new File("/Users/johnch/Desktop/full_villain.jpg"));
    
    BufferedImage mixedBag = new BufferedImage(good.getWidth(), evil.getHeight(), good.getType());
    
    int halfWidth = good.getWidth() / 2;
    
    for (int r = 0; r < mixedBag.getHeight(); ++r) {
      for (int c = 0; c < mixedBag.getWidth(); ++c) {
        if (c < halfWidth) {
          mixedBag.setRGB(c, r, good.getRGB(c, r));
        } else {
          mixedBag.setRGB(c, r, evil.getRGB(c, r));
        }
      }
    }
    
    ImageIO.write(mixedBag, "png", new File("/Users/johnch/Desktop/twoface.png"));
  }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *