Beispiel #1
0
 static BufferedImage addMagnitudes(BufferedImage img1, BufferedImage img2) {
   BufferedImage dst = new BufferedImage(img1.getWidth(), img1.getHeight(), img1.getType());
   for (int y = 0; y < img1.getHeight(); ++y) {
     for (int x = 0; x < img1.getWidth(); ++x) {
       int rgb1 = img1.getRGB(x, y);
       int rgb2 = img2.getRGB(x, y);
       int r1 = (rgb1 & 0x00FF0000) >> 16;
       int r2 = (rgb2 & 0x00FF0000) >> 16;
       int r = (int) (Math.sqrt(r1 * r1 + r2 * r2) / Math.sqrt(2.0));
       if (r > 255) r = 255;
       if (r < 0) r = 0;
       int g1 = (rgb1 & 0x0000FF00) >> 8;
       int g2 = (rgb2 & 0x0000FF00) >> 8;
       int g = (int) (Math.sqrt(g1 * g1 + g2 * g2) / Math.sqrt(2.0));
       if (g > 255) g = 255;
       if (g < 0) g = 0;
       int b1 = rgb1 & 0x000000FF;
       int b2 = rgb2 & 0x000000FF;
       int b = (int) (Math.sqrt(b1 * b1 + b2 * b2) / Math.sqrt(2.0));
       if (b > 255) b = 255;
       if (b < 0) b = 0;
       int rgb = b + (g << 8) + (r << 16);
       dst.setRGB(x, y, rgb);
     }
   }
   return dst;
 }
Beispiel #2
0
  /**
   * Synchronize the textLayout and the shape (=frame box, by calling syncFrame) with the model When
   * <code>TextLayout</code> is used, this delegates to <code>getRotation()</code> where computing
   * rotation angle is concerned, and updates the AffineTransform returned by <code>
   * getTextToModelTransform()</code>.
   */
  protected void syncShape() {
    PicText te = (PicText) element;

    //			textLayout = new TextLayout(te.getText().length()==0 ? " " : te.getText(),
    //			    textFont,
    //			    new FontRenderContext(null,false,false));

    text2ModelTr.setToIdentity(); // reset
    PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
    text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR !
    // the reference point of an image is the top-left one, but the refpoint of a text layout is on
    // the baseline
    if (image != null) {
      text2ModelTr.translate(te.getLeftX(), te.getTopY());
      if (te.getWidth() != 0
          && image.getWidth() != 0
          && (te.getDepth() + te.getHeight()) != 0
          && image.getHeight() != 0)
        text2ModelTr.scale(
            te.getWidth() / image.getWidth(),
            -(te.getHeight() + te.getDepth()) / image.getHeight());
    } else {
      // Hack ? Just cheating a little bit ? Ou juste ruse ?
      // we want here to use the dimensions of the textLayout instead of latex dimensions if
      // areDimensionsComputed
      // sinon on va aligner le textlayout en fonction des parametres latex, et l'Utilisateur (qui
      // est bien bete) ne va rien comprendre.
      double latexH = 0;
      double latexD = 0;
      double latexW = 0;
      if (areDimensionsComputed) { // store latex dimensions, and setDimensions to textLayout ones
        latexH = te.getHeight();
        latexD = te.getDepth();
        latexW = te.getWidth();
        te.setDimensions(
            textLayout.getBounds().getWidth(), textLayout.getAscent(), textLayout.getDescent());
      }
      text2ModelTr.translate(te.getLeftX(), te.getBaseLineY());
      if (areDimensionsComputed) { // restore latex dimensions
        te.setDimensions(latexW, latexH, latexD);
      }
      // Autre possibilite= comprimer le texte pour qu'il rentre dans la boite (evite le hack
      // ci-dessus):
      // text2ModelTr.scale(te.getWidth()/textLayout.getWidth(),-(te.getHeight()+te.getDepth())/textLayout.getHeight());
      text2ModelTr.scale(1.0, -1.0);
    }
    syncFrame();
  }
Beispiel #3
0
 /**
  * Scale the given BufferedImage to width and height that are powers of two. Return the new scaled
  * BufferedImage.
  */
 public static BufferedImage convertToPowerOf2(BufferedImage bsrc) {
   // find powers of 2 equal to or greater than current dimensions
   int newW = GLApp.getPowerOfTwoBiggerThan(bsrc.getWidth());
   int newH = GLApp.getPowerOfTwoBiggerThan(bsrc.getHeight());
   if (newW == bsrc.getWidth() && newH == bsrc.getHeight()) {
     return bsrc; // no change necessary
   } else {
     AffineTransform at =
         AffineTransform.getScaleInstance(
             (double) newW / bsrc.getWidth(), (double) newH / bsrc.getHeight());
     BufferedImage bdest = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
     Graphics2D g = bdest.createGraphics();
     g.drawRenderedImage(bsrc, at);
     return bdest;
   }
 }
Beispiel #4
0
 public static BufferedImage convertToARGB(BufferedImage image) {
   BufferedImage newImage =
       new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
   Graphics2D g = newImage.createGraphics();
   g.drawImage(image, 0, 0, null);
   g.dispose();
   return newImage;
 }
Beispiel #5
0
 /**
  * Scale the given BufferedImage to the given width and height. Return the new scaled
  * BufferedImage.
  */
 public static BufferedImage scale(BufferedImage bsrc, int width, int height) {
   AffineTransform at =
       AffineTransform.getScaleInstance(
           (double) width / bsrc.getWidth(), (double) height / bsrc.getHeight());
   BufferedImage bdest = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
   Graphics2D g = bdest.createGraphics();
   g.drawRenderedImage(bsrc, at);
   return bdest;
 }
 private void scaleImage() {
   Image img =
       back.getScaledInstance(scx(back.getWidth()), scy(back.getHeight()), Image.SCALE_SMOOTH);
   back =
       new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
   Graphics g = back.getGraphics();
   g.drawImage(img, 0, 0, null);
   g.dispose();
 }
  /** Prototype give player a leveled up look */
  public void Opify(double Fac) {

    for (int i = 0; i < imgCHARAC.getWidth(); i++) {
      for (int j = 0; j < imgCHARAC.getHeight(); j++) {
        if (imgCHARAC.getRGB(i, j) != imgCHARAC.getRGB(2, 2)) {
          imgCHARAC.setRGB(i, j, (int) Math.round(imgCHARAC.getRGB(i, j) * Fac));
        }
      }
    }
  }
Beispiel #8
0
  public void paint(Graphics g) {

    // image=tool.getImage(imageName);
    int h = image2.getHeight(this) / 2;
    int w = image2.getWidth(this) / 2;
    g.drawImage(image2, 150, 100, this);
    //  g.drawImage(this.image2, 150+w+30, 100,w,h,this);
    // g.drawString(imageName, 170, 50);

  }
Beispiel #9
0
 private static void initImg(BufferedImage img, int pf, int flags) throws Exception {
   WritableRaster wr = img.getRaster();
   int imgType = img.getType();
   if (imgType == BufferedImage.TYPE_INT_RGB
       || imgType == BufferedImage.TYPE_INT_BGR
       || imgType == BufferedImage.TYPE_INT_ARGB
       || imgType == BufferedImage.TYPE_INT_ARGB_PRE) {
     SinglePixelPackedSampleModel sm = (SinglePixelPackedSampleModel) img.getSampleModel();
     int pitch = sm.getScanlineStride();
     DataBufferInt db = (DataBufferInt) wr.getDataBuffer();
     int[] buf = db.getData();
     initIntBuf(buf, img.getWidth(), pitch, img.getHeight(), pf, flags);
   } else {
     ComponentSampleModel sm = (ComponentSampleModel) img.getSampleModel();
     int pitch = sm.getScanlineStride();
     DataBufferByte db = (DataBufferByte) wr.getDataBuffer();
     byte[] buf = db.getData();
     initBuf(buf, img.getWidth(), pitch, img.getHeight(), pf, flags);
   }
 }
  /**
   * do damage to character
   *
   * @param Dmg Amount of Damage
   */
  public void Damage(int Dmg, int Type) {
    // If character is already dead then dont do damage
    if (ISDEAD) return;

    // Do damage
    if (Type == 1) {
      // DAMAGE FROM PHYSICAL ATTACK
      if (STATS.ARMOR > Dmg) return;
      HEALTH = HEALTH - Dmg + STATS.ARMOR;
    } else if (Type == 2) {
      // DAMAGE FROM MAGIC ATTACK
      if (STATS.MAGIC_RESIST > Dmg) return;
      HEALTH = HEALTH - Dmg + STATS.MAGIC_RESIST;
    }
    // If an Npc then run and hide
    if (NAI != null) {
      NAI.State = "alarmed";
    }

    // Death condition
    if (HEALTH <= 0) {
      // If player is dead
      if (this.CLASS.equals("Player")) {

        HEALTH = 0;

        // Quit game
        JOptionPane.showMessageDialog(null, "You are dead");
        X = 100;
        Y = 100;
        Opify(50);
        HEALTH = (int) MAX_HEALTH;

      } else {
        // If other character
        // set Death stats
        ISDEAD = true;
        HEALTH = 0;
        // display death
        CLASS = Cl + " (Dead)";

        // Rot effect
        for (int i = 0; i < imgCHARAC.getWidth(); i++) {
          for (int j = 0; j < imgCHARAC.getHeight(); j++) {
            imgCHARAC.setRGB(i, j, imgCHARAC.getRGB(i, j) * (int) Math.pow(3, 3));
          }
        }

        // Make inventory open to looting
        INVENTORY.OPEN_INVEN = true;
      }
    }
  }
Beispiel #11
0
 public static void main(String[] args) throws Exception {
   Robot robot = new Robot(args[0]);
   BufferedImage oimg = robot.cam.capture(true);
   // BufferedImage img = maslab.camera.ImageUtil.convertImage(oimg, BufferedImage.TYPE_INT_RGB);
   BufferedImage img =
       new BufferedImage(oimg.getWidth(), oimg.getHeight(), BufferedImage.TYPE_INT_RGB);
   for (int y = 0; y < oimg.getHeight(); ++y) {
     for (int x = 0; x < oimg.getWidth(); ++x) {
       img.setRGB(x, y, oimg.getRGB(x, y));
     }
   }
   BufferedImage blurred = gaussianBlur(img);
   ImageIO.write(blurred, "bmp", new File("gaussian.bmp"));
   BufferedImage xe = sobelX(blurred);
   ImageIO.write(xe, "bmp", new File("sobelx.bmp"));
   BufferedImage ye = sobelY(blurred);
   ImageIO.write(ye, "bmp", new File("sobely.bmp"));
   BufferedImage edges = addMagnitudes(xe, ye);
   BufferedImage dst = edges;
   ImageIO.write(dst, "bmp", new File("edges.bmp"));
 }
Beispiel #12
0
 public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
   if (image != null && showimage) {
     // TODO: add ability to scale maintaining aspect ratio fitting to size of parent
     // TODO: Need to add not zoom all the way, but zoom to a box of aspect ratio 4/3
     Graphics2D g2 = (Graphics2D) g;
     AffineTransform tran = new AffineTransform(1f, 0f, 0f, 1f, 0, 0);
     float widthscale = (float) c.getWidth() / image.getWidth();
     float heightscale = (float) c.getHeight() / image.getHeight();
     switch (drawmode) {
       case DRAW_MODE_ASPECT:
         float scale;
         if (widthscale < heightscale) {
           scale = widthscale;
         } else {
           scale = heightscale;
         }
         tran.scale(scale, scale);
         g2.drawImage(
             image,
             new AffineTransformOp(tran, AffineTransformOp.TYPE_BILINEAR),
             (int) (c.getWidth() - image.getWidth() * scale) / 2,
             (int) (c.getHeight() - image.getHeight() * scale) / 2);
         break;
       case DRAW_MODE_WIDTH:
         tran.scale(widthscale, widthscale);
         g2.drawImage(image, tran, null);
         break;
       case DRAW_MODE_HEIGHT:
         tran.scale(heightscale, heightscale);
         g2.drawImage(image, tran, null);
         break;
       default:
         tran.scale(widthscale, heightscale);
         g2.drawImage(image, tran, null);
         break;
     }
   }
 }
Beispiel #13
0
 public Button(String filename, String filenameHov, int x, int y) {
   File normal = new File(filename);
   File hovered = new File(filenameHov);
   try {
     imageNormal = ImageIO.read(normal);
     imageHovered = ImageIO.read(hovered);
   } catch (Exception e) {
     System.out.println("Picture not working");
   }
   width = imageNormal.getWidth();
   height = imageNormal.getHeight();
   this.x = x;
   this.y = y;
 }
Beispiel #14
0
  private BufferedImage convert(BufferedImage image, int imageType) {
    if (image.getType() == imageType) {
      return image;
    }

    int w = image.getWidth();
    int h = image.getHeight();
    BufferedImage newImg = new BufferedImage(w, h, imageType);
    ColorSpace srcSpace = image.getColorModel().getColorSpace();
    ColorSpace newSpace = newImg.getColorModel().getColorSpace();
    ColorConvertOp convert = new ColorConvertOp(srcSpace, newSpace, null);
    convert.filter(image, newImg);
    return newImg;
  }
    Sidebar() {
      super(BoxLayout.Y_AXIS);

      try {
        back =
            ImageIO.read(
                ClassLoader.getSystemClassLoader()
                    .getResource("org/madeirahs/editor/ui/help_sidebar.png"));
        scaleImage();
        setPreferredSize(new Dimension(back.getWidth(), back.getHeight()));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
Beispiel #16
0
  /*
   * Method takes a parameter of a BufferedImage
   * and returns a 2d array
   */
  public static int[][] readIntoArray(BufferedImage x) {
    int width = x.getWidth();
    int height = x.getHeight();

    // initialize the 2d array to the size of the picture
    int[][] imagePixels = new int[width][height];

    for (int i = 0; i < width; i++) {
      for (int j = 0; j < height; j++) {
        imagePixels[i][j] = x.getRGB(i, j); // store RGB value in array
        //     printPixelARGB(x.getRGB(i,j));
      }
    }
    return imagePixels;
  }
Beispiel #17
0
  /** Scale this GLImage so width and height are powers of 2. Recreate pixels and pixelBuffer. */
  public void convertToPowerOf2() {
    // make BufferedImage from original pixels
    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    image.setRGB(0, 0, w, h, pixels, 0, w);

    // scale into new image
    BufferedImage scaledImg = convertToPowerOf2(image);

    // resample pixel data
    w = scaledImg.getWidth(null);
    h = scaledImg.getHeight(null);
    pixels = getImagePixels(scaledImg); // pixels in default Java ARGB format
    pixelBuffer = convertImagePixelsRGBA(pixels, w, h, false); // convert to bytes in RGBA format
    textureW = GLApp.getPowerOfTwoBiggerThan(w); // the texture size big enough to hold this image
    textureH = GLApp.getPowerOfTwoBiggerThan(h); // the texture size big enough to hold this image
  }
 @Override
 public void paintComponent(Graphics g) {
   g.setColor(getBackground());
   g.fillRect(0, 0, getWidth(), getHeight());
   int w = bufferedImage.getWidth(this);
   int h = bufferedImage.getHeight(this);
   if (mode == Flip.NONE) {
     g.drawImage(bufferedImage, 0, 0, w, h, this);
   } else if (mode == Flip.VERTICAL) {
     AffineTransform at = AffineTransform.getScaleInstance(1d, -1d);
     at.translate(0, -h);
     Graphics2D g2 = (Graphics2D) g.create();
     g2.drawImage(bufferedImage, at, this);
     g2.dispose();
   } else if (mode == Flip.HORIZONTAL) {
     AffineTransform at = AffineTransform.getScaleInstance(-1d, 1d);
     at.translate(-w, 0);
     AffineTransformOp atOp = new AffineTransformOp(at, null);
     g.drawImage(atOp.filter(bufferedImage, null), 0, 0, w, h, this);
   }
 }
Beispiel #19
0
 public CA toScaledCA(float scale) {
   int w = _i.getWidth();
   int h = _i.getHeight();
   /*
   BufferedImage scaled = new BufferedImage((int)(w*scale), (int)(h*scale), BufferedImage.TYPE_INT_ARGB);
   AffineTransform at = new AffineTransform();
   at.scale(scale, scale);
   RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
   hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
   hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
   AffineTransformOp scaleOp = new AffineTransformOp(at, hints);
   scaled = scaleOp.filter(_i, scaled);
   return new CA(scaled);
   */
   return new CA(
       Scalr.resize(
           _i,
           Scalr.Method.ULTRA_QUALITY,
           (int) (w * scale),
           (int) (h * scale),
           Scalr.OP_ANTIALIAS,
           Scalr.OP_BRIGHTER));
 }
Beispiel #20
0
  public ImageFont(String pathToImage, int numCols, int numRows) {
    try {
      tilesImg = convertToARGB(ImageIO.read(new File(pathToImage)));

      this.imgW = tilesImg.getWidth();
      this.imgH = tilesImg.getHeight();
      this.numCols = numCols;
      this.numRows = numRows;
      this.numTiles = numCols * numRows;
      this.tW = this.imgW / this.numCols;
      this.tH = this.imgH / this.numRows;

      this.tiles = new BufferedImage[this.numTiles];

      for (int i = 0; i < numCols; i++) {
        for (int j = 0; j < numRows; j++) {
          tiles[(numCols * j) + i] = tilesImg.getSubimage(i * tW, j * tH, tW, tH);
        }
      }
    } catch (IOException e) {
      System.out.println("Couldn't load the image: " + e);
    }
  }
Beispiel #21
0
 /**
  * Load an image from the given filename. If convertToPow2 is true then convert the image to a
  * power of two. Store pixels as ARGB ints in the pixels array and as RGBA bytes in the
  * pixelBuffer ByteBuffer. Hold onto image width/height.
  *
  * @param imgName
  */
 public boolean makeGLImage(BufferedImage tmpi, boolean flipYaxis, boolean convertToPow2) {
   if (tmpi != null) {
     if (flipYaxis) {
       tmpi = flipY(tmpi);
     }
     if (convertToPow2) {
       tmpi = convertToPowerOf2(tmpi);
     }
     w = tmpi.getWidth(null);
     h = tmpi.getHeight(null);
     pixels = getImagePixels(tmpi); // pixels in default Java ARGB format
     pixelBuffer = convertImagePixelsRGBA(pixels, w, h, false); // convert to bytes in RGBA format
     textureW = GLApp.getPowerOfTwoBiggerThan(w); // the texture size big enough to hold this image
     textureH = GLApp.getPowerOfTwoBiggerThan(h); // the texture size big enough to hold this image
     // GLApp.msg("GLImage: loaded " + imgName + ", width=" + w + " height=" + h);
     return true;
   } else {
     // GLApp.err("GLImage: FAILED TO LOAD IMAGE " + imgName);
     pixels = null;
     pixelBuffer = null;
     h = w = 0;
     return false;
   }
 }
Beispiel #22
0
  private IFD writeCMYKImage(ImageOutputStream out, BufferedImage image, TIFFImageWriteParam param)
      throws IOException {
    try {
      int width = image.getWidth();
      int height = image.getHeight();

      IFD ifd = new IFD(); // entries need to be in tag order !

      ifd.add(new DEFactory.NewSubfileTypeDE(2)); // 254 single page of multipage file
      ifd.add(new DEFactory.ImageWidthDE(width)); // 256
      ifd.add(new DEFactory.ImageLengthDE(height)); // 257

      DEFactory.BitsPerSampleDE bpss = new DEFactory.BitsPerSampleDE(4);
      bpss.setBitsPerSample(0, 8); // cyan
      bpss.setBitsPerSample(1, 8); // magneta
      bpss.setBitsPerSample(2, 8); // yellow
      bpss.setBitsPerSample(3, 8); // key (black)
      ifd.add(bpss); // 258

      ifd.add(new DEFactory.CompressionDE(NOCOMPRESSION)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(CMYK)); // 262

      int maxrps, maxstripes; // max RowsPerStrip
      if ((1 << 13) <= width) {
        maxrps = 1;
        maxstripes = height; // one row per strip
      } else {
        maxrps = (1 << 13) / width;
        maxstripes = (height + maxrps - 1) / maxrps;
      }

      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.SamplesPerPixelDE(4)); // 277
      ifd.add(new DEFactory.RowsPerStripDE(maxrps)); // 278
      DEFactory.StripByteCountsDE counts = new DEFactory.StripByteCountsDE(maxstripes);
      ifd.add(counts); // 279

      if (param == null) {
        ifd.add(new DEFactory.XResolutionDE(72.0)); // 282
        ifd.add(new DEFactory.YResolutionDE(72.0)); // 283
      } else {
        ifd.add(new DEFactory.XResolutionDE(param.getXResolution())); // 282
        ifd.add(new DEFactory.YResolutionDE(param.getYResolution())); // 283
      }
      ifd.add(new DEFactory.ResolutionUnitDE(Inch)); // 296

      int index = 0;
      for (int y = 0; y < height; y += maxrps) {
        /*
        Assume rgb image.

        Each strip: evaluate c m y k colour
                    save in byte array
                    write to image file
        */

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        for (int i = 0; i < maxrps; i++) {
          if ((y + i) == height) {
            break;
          } // last strip might have less rows
          for (int x = 0; x < width; x++) {
            int c = image.getRGB(x, y + i);

            int R = (c >> 16) & 0x00FF;
            int G = (c >> 8) & 0x00FF;
            int B = (c) & 0x00FF;

            if ((R == 255) && (G == 255) && (B == 255)) {
              baos.write(0);
              baos.write(0);
              baos.write(0);
              baos.write(0);
            } else {
              double C = 1.0 - R / 255.0;
              double M = 1.0 - G / 255.0;
              double Y = 1.0 - B / 255.0;

              double K = C;
              if (M < K) {
                K = M;
              }
              if (Y < K) {
                K = Y;
              }

              C = ((C - K) / (1.0 - K)) * 255.0;
              M = ((M - K) / (1.0 - K)) * 255.0;
              Y = ((Y - K) / (1.0 - K)) * 255.0;
              K *= 255.0;

              baos.write((int) C);
              baos.write((int) M);
              baos.write((int) Y);
              baos.write((int) K);
            }
          }
        }
        baos.close();

        byte[] data = baos.toByteArray();
        counts.setCount(index, data.length); // update ifd strip counter array
        offsets.setOffset(index, out.getStreamPosition()); // update ifd image data offset array
        out.write(data); // write to image stream

        index++;
      }
      return ifd;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(getClass().getName() + ".writeCMYKImage:\n\t" + e.getMessage());
    }
  }
Beispiel #23
0
  private void makeMenuScreen() {
    menu = new JPanel();
    menu.setBackground(Color.BLACK);
    menu.setLayout(null);
    menu.setBounds(0, 0, width, height);

    try {
      BufferedImage menuIMG =
          ImageIO.read(this.getClass().getResource("/Resources/MenuBackground.png"));
      // BufferedImage menuIMG = ImageIO.read(new
      // File("M:/ComputerProgrammingJava/InsaneMouse_03/src/Resources/MenuBackground.png"));
      menuIMGL =
          new JLabel(
              new ImageIcon(
                  menuIMG.getScaledInstance(
                      (int) (width * 0.8), (int) (height * 0.8), Image.SCALE_SMOOTH)));
      menuIMGL.setBounds(0, 0, width, height);
    } catch (Exception e) {
    }

    highscoreL = new JLabel(String.valueOf(highscore));
    highscoreL.setBackground(Color.darkGray);
    highscoreL.setBounds((width / 2) + 100, (height / 2) + 70, 500, 100);
    highscoreL.setForeground(Color.white);

    easy = new JButton("Easy");
    hard = new JButton("Hard");

    easy.addActionListener(this);
    hard.addActionListener(this);

    easy.setBounds((width / 2) - 60, (height / 2) - 50, 120, 20);
    hard.setBounds((width / 2) - 60, height / 2 - 10, 120, 20);

    onePlayerRB = new JRadioButton("One Player");
    twoPlayerRB = new JRadioButton("Two Player");
    mouseRB = new JRadioButton("Mouse (Player 1)");
    keyboardRB = new JRadioButton("Keyboard (Player 1)");
    keyboardSpeedS1 = new JSlider(JSlider.HORIZONTAL, 10, 300, 50);
    keyboardSpeedS2 = new JSlider(JSlider.HORIZONTAL, 10, 300, 50);
    musicCB = new JCheckBox("Music");

    onePlayerRB.setBackground(null);
    twoPlayerRB.setBackground(null);
    mouseRB.setBackground(null);
    keyboardRB.setBackground(null);
    keyboardSpeedS1.setBackground(null);
    keyboardSpeedS2.setBackground(null);
    musicCB.setBackground(null);

    onePlayerRB.setForeground(Color.WHITE);
    twoPlayerRB.setForeground(Color.WHITE);
    mouseRB.setForeground(Color.WHITE);
    keyboardRB.setForeground(Color.WHITE);
    keyboardSpeedS1.setForeground(Color.WHITE);
    keyboardSpeedS2.setForeground(Color.WHITE);
    musicCB.setForeground(Color.WHITE);

    ButtonGroup playerChoice = new ButtonGroup();
    playerChoice.add(onePlayerRB);
    playerChoice.add(twoPlayerRB);
    onePlayerRB.setSelected(true);

    ButtonGroup peripheralChoice = new ButtonGroup();
    peripheralChoice.add(mouseRB);
    peripheralChoice.add(keyboardRB);
    mouseRB.setSelected(true);

    musicCB.setSelected(true);

    onePlayerRB.setBounds((width / 2) + 100, (height / 2) - 50, 100, 20);
    twoPlayerRB.setBounds((width / 2) + 100, (height / 2) - 30, 100, 20);
    mouseRB.setBounds((width / 2) + 100, (height / 2), 200, 20);
    keyboardRB.setBounds((width / 2) + 100, (height / 2) + 20, 200, 20);
    keyboardSpeedS1.setBounds(width / 2 - 120, height / 2 + 100, 200, 50);
    keyboardSpeedS2.setBounds(width / 2 - 120, height / 2 + 183, 200, 50);
    musicCB.setBounds((width / 2) + 100, (height / 2) + 50, 100, 20);

    keyboardSpeedL1 = new JLabel("Keyboard Speed (Player One)");
    keyboardSpeedL1.setForeground(Color.WHITE);
    keyboardSpeedL1.setBounds(width / 2 - 113, height / 2 + 67, 200, 50);

    keyboardSpeedL2 = new JLabel("Keyboard Speed (Player Two)");
    keyboardSpeedL2.setForeground(Color.WHITE);
    keyboardSpeedL2.setBounds(width / 2 - 113, height / 2 + 150, 200, 50);

    howTo = new JButton("How To Play");
    howTo.addActionListener(this);
    howTo.setBounds((width / 2) - 60, height / 2 + 30, 120, 20);

    try {
      BufferedImage howToIMG = ImageIO.read(this.getClass().getResource("/Resources/HowTo.png"));
      // BufferedImage howToIMG = ImageIO.read(new
      // File("M:/ComputerProgrammingJava/InsaneMouse_03/src/Resources/HowTo.png"));
      howToIMGL = new JLabel(new ImageIcon(howToIMG));
      howToIMGL.setBounds(
          width / 2 - howToIMG.getWidth() / 2,
          height / 2 - howToIMG.getHeight() / 2,
          howToIMG.getWidth(),
          howToIMG.getHeight());
    } catch (Exception e) {
    }

    howToBack = new JButton("X");
    howToBack.setBounds(
        (int) (width / 2 + width * 0.25) - 50, (int) (height / 2 - height * 0.25), 50, 50);
    howToBack.setBackground(Color.BLACK);
    howToBack.setForeground(Color.WHITE);
    howToBack.addActionListener(this);

    menu.add(easy);
    menu.add(hard);
    menu.add(howTo);
    menu.add(highscoreL);
    menu.add(onePlayerRB);
    menu.add(twoPlayerRB);
    menu.add(mouseRB);
    menu.add(keyboardRB);
    menu.add(keyboardSpeedL1);
    menu.add(keyboardSpeedL2);
    menu.add(keyboardSpeedS1);
    menu.add(keyboardSpeedS2);
    menu.add(musicCB);
    menu.add(menuIMGL);

    back = new JButton("Back");
    back.setBounds(width / 2 - 40, height / 2, 100, 20);
    back.addActionListener(this);
    back.setVisible(false);
    this.add(back);
  }
Beispiel #24
0
  private IFD writeBModHufImage(
      ImageOutputStream out, BufferedImage image, TIFFImageWriteParam param) throws IOException {
    try {
      int width = image.getWidth();
      int height = image.getHeight();

      IFD ifd = new IFD(); // entries need to be in tag order !

      ifd.add(new DEFactory.NewSubfileTypeDE(2)); // 254 single page of multipage file
      ifd.add(new DEFactory.ImageWidthDE(width)); // 256
      ifd.add(new DEFactory.ImageLengthDE(height)); // 257
      ifd.add(new DEFactory.CompressionDE(CCITTGROUP3MODHUFFMAN)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(WhiteIsZero)); // 262

      int maxrps, maxstripes; // max RowsPerStrip
      if ((1 << 13) <= width) {
        maxrps = 1;
        maxstripes = height; // one row per stripe
      } else {
        maxrps = (1 << 13) / width;
        maxstripes = (height + maxrps - 1) / maxrps;
      }

      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.RowsPerStripDE(maxrps)); // 278
      DEFactory.StripByteCountsDE counts = new DEFactory.StripByteCountsDE(maxstripes);
      ifd.add(counts); // 279

      if (param == null) {
        ifd.add(new DEFactory.XResolutionDE(72.0)); // 282
        ifd.add(new DEFactory.YResolutionDE(72.0)); // 283
      } else {
        ifd.add(new DEFactory.XResolutionDE(param.getXResolution())); // 282
        ifd.add(new DEFactory.YResolutionDE(param.getYResolution())); // 283
      }
      ifd.add(new DEFactory.ResolutionUnitDE(Inch)); // 296

      int index = 0;
      for (int y = 0; y < height; y += maxrps) {
        /*
        Assume bilevel image (black/white[=-1])

        Each strip: count run length
                    encode into modified hufman codes
                    swap bits
                    save in byte array
                    write to image file
        */

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BitSwapOutputStream bsos = new BitSwapOutputStream(baos);
        ModHuffmanOutputStream mhos = new ModHuffmanOutputStream(bsos);

        RLEOutputStream rlos =
            new RLEOutputStream(mhos, 3); // rgb = 3 bytes per sample code word (not needed here)

        for (int i = 0; i < maxrps; i++) {
          if ((y + i) == height) {
            break;
          } // last strip might have less rows
          rlos.setStartCodeWord(-1); // white run first
          for (int x = 0; x < width; x++) {
            rlos.write(image.getRGB(x, y + i));
          }
          rlos.flush(); // write padding after ever image row
        }
        rlos.close();

        byte[] data = baos.toByteArray();
        counts.setCount(index, data.length); // update ifd strip counter array
        offsets.setOffset(index, out.getStreamPosition()); // update ifd image data offset array
        out.write(data); // write to image stream

        index++;
      }
      return ifd;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(getClass().getName() + ".writeBModHufImage:\n\t" + e.getMessage());
    }
  }
Beispiel #25
0
  private IFD writeRGBImage(
      ImageOutputStream out, BufferedImage image, int comp, TIFFImageWriteParam param)
      throws IOException {
    image = convert(image, BufferedImage.TYPE_INT_RGB);
    try {
      int width = image.getWidth();
      int height = image.getHeight();

      IFD ifd = new IFD(); // entries need to be in tag order !

      ifd.add(new DEFactory.NewSubfileTypeDE(2)); // 254 single page of multipage file
      ifd.add(new DEFactory.ImageWidthDE(width)); // 256
      ifd.add(new DEFactory.ImageLengthDE(height)); // 257

      DEFactory.BitsPerSampleDE bpss = new DEFactory.BitsPerSampleDE(3);
      bpss.setBitsPerSample(0, 8); // red
      bpss.setBitsPerSample(1, 8); // green
      bpss.setBitsPerSample(2, 8); // blue
      ifd.add(bpss); // 258

      ifd.add(new DEFactory.CompressionDE(comp)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(RGB)); // 262

      int maxrps, maxstripes; // max RowsPerStrip
      if ((1 << 13) <= width) {
        maxrps = 1;
        maxstripes = height; // one row per strip
      } else {
        maxrps = (1 << 13) / width;
        maxstripes = (height + maxrps - 1) / maxrps;
      }
      if (comp == JPEG) {
        maxrps = ((maxrps + 8 - 1) / 8) * 8;
        maxstripes = (height + maxrps - 1) / maxrps;
      }
      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.SamplesPerPixelDE(3)); // 277
      ifd.add(new DEFactory.RowsPerStripDE(maxrps)); // 278
      DEFactory.StripByteCountsDE counts = new DEFactory.StripByteCountsDE(maxstripes);
      ifd.add(counts); // 279
      if (param == null) {
        ifd.add(new DEFactory.XResolutionDE(72.0)); // 282
        ifd.add(new DEFactory.YResolutionDE(72.0)); // 283
      } else {
        ifd.add(new DEFactory.XResolutionDE(param.getXResolution())); // 282
        ifd.add(new DEFactory.YResolutionDE(param.getYResolution())); // 283
      }
      ifd.add(new DEFactory.ResolutionUnitDE(Inch)); // 296

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStream os = baos;
      JPEGOutputStream jpegos = null;

      if (comp == JPEG) { // add JPEGTables tag
        jpegos = new JPEGOutputStream(baos);

        int quality = (param == null) ? 50 : (int) (param.getCompressionQuality() * 100);

        jpegos.setZZQuantizationTable(0, JPEGConstants.LQT, quality);
        jpegos.setRawDCHuffmanTable(0, JPEGConstants.HLDCTable);
        jpegos.setRawACHuffmanTable(0, JPEGConstants.HLACTable);

        jpegos.defineQuantizationTables();
        jpegos.defineHuffmanTables();
        jpegos.close();

        DEFactory.JPEGTablesDE jpegtables = new DEFactory.JPEGTablesDE(baos.toByteArray());
        ifd.add(jpegtables); // 347

        baos.reset();

        os = jpegos;
      }

      WritableRaster raster = image.getRaster();
      DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();
      int[] imgdata = (int[]) buffer.getData();

      int index = 0;
      for (int y = 0; y < height; y += maxrps) {
        /*
        Assume rgb image.

        Each strip: evaluate r g b colour
                    save in byte array
                    write to image file
        */

        if ((height - y) < maxrps) {
          maxrps = height - y;
        }

        if (jpegos != null) { // jpeg: SOI,SOF,SOS marker
          jpegos.startOfImage();
          int[] hv = {0x11, 0x11, 0x11}; // (Hi<<4)|Vi
          int[] q = {0, 0, 0}; // quantization table 0
          jpegos.startOfFrame(maxrps, width, hv, q);
          int[] sel = {0, 0, 0}; // DC,AC code table 0
          jpegos.startOfScan(sel);
        }

        for (int i = 0; i < maxrps; i++) { // write RGB data
          for (int x = 0; x < width; x++) {
            int c = imgdata[x + (y + i) * width];
            os.write((c >> 16) & 0x000000FF);
            os.write((c >> 8) & 0x000000FF);
            os.write(c & 0x000000FF);
          }
        }
        os.close(); // jpeg: EOI marker

        byte[] data = baos.toByteArray();
        counts.setCount(index, data.length); // update ifd strip counter array
        offsets.setOffset(index, out.getStreamPosition()); // update ifd image data offset array
        out.write(data); // write to image stream
        baos.reset();
        index++;
      }
      return ifd;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(getClass().getName() + ".writeRGBImage:\n\t" + e.getMessage());
    }
  }
Beispiel #26
0
 public int getHeight() {
   return _i.getHeight();
 }
Beispiel #27
0
  public erosion(String nombre) {

    imageName = nombre;

    // BufferedImage image2;
    String aux;

    // int ancho=image.getWidth();

    // BufferedImage image = ImageIO.read( new File( imageName ) );
    try {
      image = ImageIO.read(new File(imageName));
    } catch (IOException e) {
      System.out.println("image missing");
    }

    try {
      image2 = ImageIO.read(new File(imageName));
    } catch (IOException e) {
      System.out.println("image missing");
    }

    int k;
    int a;
    int b;
    int i;
    int j;

    int rojo;
    int verde;
    int azul;

    int promedio;
    try {
      int ancho, alto;
      alto = image.getHeight();
      ancho = image.getWidth();
      for (i = 0; i < ancho; i++) {
        for (j = 0; j < alto; j++) {
          k = image.getRGB(i, j);
          k = 0xFFFFFF + k;

          rojo = k / 0x10000;

          k = k % 0x10000;
          verde = k / 0x100;

          k = k % 0x100;
          azul = k;

          if (rojo < 0) rojo = 255 + rojo;
          if (verde < 0) verde = 255 + verde;
          if (azul < 0) azul = 255 + azul;

          promedio = azul + verde + rojo;
          promedio = promedio / 3;
          /*if(promedio<0)
          promedio=promedio+128;*/

          rojo = promedio;
          verde = promedio;
          azul = promedio;
          // printf("")

          if (promedio >= 128) promedio = 255;
          else promedio = 0;
          k = promedio + promedio * 0x100 + promedio * 0x10000;

          this.image.setRGB(i, j, k);
        }
      }
    } catch (Exception e) {
      System.out.printf("n");
    }
    //
    try {
      int ancho, alto;
      alto = image2.getHeight();
      ancho = image2.getWidth();
      for (i = 0; i < ancho; i++) {
        for (j = 0; j < alto; j++) {
          k = image2.getRGB(i, j);
          k = 0xFFFFFF + k;

          rojo = k / 0x10000;

          k = k % 0x10000;
          verde = k / 0x100;

          k = k % 0x100;
          azul = k;

          if (rojo < 0) rojo = 255 + rojo;
          if (verde < 0) verde = 255 + verde;
          if (azul < 0) azul = 255 + azul;

          promedio = azul + verde + rojo;
          promedio = promedio / 3;
          /*if(promedio<0)
          promedio=promedio+128;*/

          rojo = promedio;
          verde = promedio;
          azul = promedio;
          // printf("")

          k = promedio + promedio * 0x100 + promedio * 0x10000;

          this.image2.setRGB(i, j, k);
        }
      }
    } catch (Exception e) {
      System.out.printf("n");
    }

    //
    try {
      int ancho, alto;
      alto = image.getHeight();
      ancho = image.getWidth();
      for (i = 0; i < ancho; i++) {
        for (j = 0; j < alto; j++) {
          k = image.getRGB(i, j);
          k = 0xFFFFFF + k;

          rojo = k / 0x10000;

          k = k % 0x10000;
          verde = k / 0x100;

          k = k % 0x100;
          azul = k;

          if (rojo < 0) rojo = 255 + rojo;
          if (verde < 0) verde = 255 + verde;
          if (azul < 0) azul = 255 + azul;

          /*promedio=azul+verde+rojo;
          promedio=promedio/3;
          /*if(promedio<0)
           promedio=promedio+128;*/

          if (i < ancho - 2) {
            if (rojo >= 128) {
              k = image.getRGB(i + 1, j);
              k = 0xFFFFFF + k;

              rojo = k / 0x10000;

              k = k % 0x10000;
              verde = k / 0x100;

              k = k % 0x100;
              azul = k;

              if (rojo < 0) rojo = 255 + rojo;
              if (verde < 0) verde = 255 + verde;
              if (azul < 0) azul = 255 + azul;

              if (rojo >= 128) {
                k = image.getRGB(i + 2, j);
                k = 0xFFFFFF + k;

                rojo = k / 0x10000;

                k = k % 0x10000;
                verde = k / 0x100;

                k = k % 0x100;
                azul = k;

                if (rojo < 0) rojo = 255 + rojo;
                if (verde < 0) verde = 255 + verde;
                if (azul < 0) azul = 255 + azul;
                if (rojo < 128) {
                  k = 0;
                  this.image2.setRGB(i, j, k);
                  this.image2.setRGB(i + 1, j, k);
                  this.image2.setRGB(i + 2, j, k);
                }
              }

            } else {
              k = rojo + rojo * 0x100 + rojo * 0x10000;
              this.image2.setRGB(i, j, k);
            }
          }
        }
      }
    } catch (Exception e) {
      System.out.printf("n");
    }
    //

    /*else if(l==4)
    posterizacion();*/

    // Toolkit tool = Toolkit.getDefaultToolkit();
    // image = tool.getImage(imageName);

    // dialogo.setLocationRelativeTo(f);

  }
  /**
   * Binds the BufferedImage byte-stream into video memory. BufferedImage must be in 4BYTE_ABGR.
   * 4BYTE_ABGR removes endinese problems.
   */
  public Texture bind(final BufferedImage _image, final InternalFormat _format) {
    final GL3 gl = GLRenderer.getCanvas().getContext().getCurrentGL().getGL3();
    if (gl == null) {
      System.out.println("GL context doesn't exist");
      return null;
    }

    gl.glEnable(GL.GL_TEXTURE_2D);

    final int textureID = glGenTextures(gl);
    gl.glBindTexture(GL3.GL_TEXTURE_2D, textureID);

    gl.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_WRAP_S, GL3.GL_REPEAT);
    gl.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_WRAP_T, GL3.GL_REPEAT);
    gl.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_MAG_FILTER, GL3.GL_LINEAR);
    gl.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_MIN_FILTER, GL3.GL_LINEAR_MIPMAP_LINEAR);

    final int width = _image.getWidth();
    final int height = _image.getHeight();
    final int channels = _image.getSampleModel().getNumBands();
    int internalFormat = GL3.GL_RGB;

    if (gl.isExtensionAvailable("GL_EXT_abgr") == true) {
      switch (channels) {
        case 4:
          imageFormat = GL2.GL_ABGR_EXT;
          break;
        case 3:
          imageFormat = GL3.GL_BGR;
          break;
        case 1:
          imageFormat = GL3.GL_RED;
          break;
      }
    } else {
      switch (channels) {
        case 4:
          imageFormat = GL3.GL_RGBA;
          break;
        case 3:
          imageFormat = GL3.GL_RGB;
          break;
        case 1:
          imageFormat = GL3.GL_RED;
          break;
      }
    }

    gl.glPixelStorei(GL3.GL_UNPACK_ALIGNMENT, 1);
    gl.glTexImage2D(
        GL3.GL_TEXTURE_2D,
        0,
        getGLInternalFormat(channels, _format),
        width,
        height,
        0,
        imageFormat,
        GL3.GL_UNSIGNED_BYTE,
        getByteBuffer(_image));

    gl.glGenerateMipmap(GL3.GL_TEXTURE_2D);
    gl.glBindTexture(GL.GL_TEXTURE_2D, 0); // Reset to default texture

    return new Texture(new GLImage(textureID, width, height));
  }
  public void insertBuilding(int i, int j, int index) {

    if (!tiles[i][j].getValue().equals("")) {
      JOptionPane.showMessageDialog(null, "There is already a building here");
      return;
    }

    String temp = bb.get(index).getText();
    String[] parts = temp.split("-");

    int newQ = Integer.parseInt(parts[1]) - 1;
    if (newQ < 0) return;

    Building tB = bList.get(0);
    for (int b = 0; b < bList.size(); b++) {
      if (bList.get(b).getName().equals(parts[0])) {
        tB = bList.get(b);
        // System.out.println("here");
        break;
      }
    }

    Image image = null;
    BufferedImage buffered;
    try {
      image = ImageIO.read(new File("images/" + tB.getName().replace(" ", "_") + ".png"));
      System.out.println("Loaded image");
    } catch (IOException e) {
      System.out.println("Failed to load image");
    }
    buffered = (BufferedImage) image;

    for (int c = 0; c < tB.getQWidth(); c++) {
      for (int r = 0; r < tB.getQHeight(); r++) {
        if (i + c == 40 || j + r == 40) {
          JOptionPane.showMessageDialog(null, "Placing a building here would be out of bounds");
          return;
        }

        if (!tiles[i + c][j + r].getValue().equals("")) {
          JOptionPane.showMessageDialog(null, "Placing a building here will result to a overlap");
          return;
        }
      }
    }

    double w = buffered.getWidth() / tB.getQWidth();
    double h = buffered.getHeight() / tB.getQHeight();

    for (int c = 0; c < tB.getQWidth(); c++) {
      for (int r = 0; r < tB.getQHeight(); r++) {
        tiles[i + c][j + r].setBackground(new Color(51, 204, 51));
        tiles[i + c][j + r].setIcon(
            new ImageIcon(
                resize(
                    buffered.getSubimage((int) w * r, (int) h * c, (int) w, (int) h),
                    tiles[i + c][j + r].getWidth(),
                    tiles[i + c][j + r].getHeight())));

        String tValue = (c == 0 && r == 0) ? tB.getName() : i + "-" + j;
        // System.out.println(tValue);
        tiles[i + c][j + r].setValue(tValue);
      }
    }

    // tiles[i][j].setBackground(Color.BLUE);
    bb.get(index).setText(parts[0] + "-" + newQ);
  }
Beispiel #30
0
  private IFD writeYCbCrImage(
      ImageOutputStream out, BufferedImage image, int comp, TIFFImageWriteParam param)
      throws IOException {
    image = convert(image, BufferedImage.TYPE_INT_RGB);
    try {
      int width = image.getWidth();
      int height = image.getHeight();

      IFD ifd = new IFD(); // entries need to be in tag order !

      int ss = (param == null) ? 0x22 : param.getSubSampling();

      int ssh = (ss >> 4) & 0x0F;
      int ssv = ss & 0x0F;

      if (ssh
          < ssv) { // YCbCrSubsampleVert shall always be less than or equal to YCbCrSubsampleHoriz.
        throw new IOException(
            "Internal error: YCbCrSubsampleVert is not less than YCbCrSubsampleHoriz.");
      }

      //      int ww=((width +ssh-1)/ssh)*ssh;                                   // [1] p.92
      //      int hh=((height+ssv-1)/ssv)*ssv;
      int ww = width;
      int hh = height;

      ifd.add(new DEFactory.NewSubfileTypeDE(2)); // 254 single page of multipage file
      ifd.add(new DEFactory.ImageWidthDE(ww)); // 256
      ifd.add(new DEFactory.ImageLengthDE(hh)); // 257

      DEFactory.BitsPerSampleDE bpss = new DEFactory.BitsPerSampleDE(3);
      bpss.setBitsPerSample(0, 8); // Y
      bpss.setBitsPerSample(1, 8); // Cb
      bpss.setBitsPerSample(2, 8); // Cr
      ifd.add(bpss); // 258

      ifd.add(new DEFactory.CompressionDE(comp)); // 259
      ifd.add(new DEFactory.PhotometricInterpretationDE(YCbCr)); // 262

      int maxrps, maxstripes; // max RowsPerStrip
      if ((1 << 13) <= width) {
        maxrps = 1;
        maxstripes = height; // one row per strip
      } else {
        maxrps = (1 << 13) / width;
        maxstripes = (height + maxrps - 1) / maxrps;
      }
      if (comp == JPEG) {
        maxrps = ((maxrps + 8 * ssv - 1) / (8 * ssv)) * (8 * ssv);
        maxstripes = (height + maxrps - 1) / maxrps;
      }

      DEFactory.StripOffsetsDE offsets = new DEFactory.StripOffsetsDE(maxstripes);
      ifd.add(offsets); // 273
      ifd.add(new DEFactory.SamplesPerPixelDE(3)); // 277
      ifd.add(new DEFactory.RowsPerStripDE(maxrps)); // 278
      DEFactory.StripByteCountsDE counts = new DEFactory.StripByteCountsDE(maxstripes);
      ifd.add(counts); // 279

      if (param == null) {
        ifd.add(new DEFactory.XResolutionDE(72.0)); // 282
        ifd.add(new DEFactory.YResolutionDE(72.0)); // 283
      } else {
        ifd.add(new DEFactory.XResolutionDE(param.getXResolution())); // 282
        ifd.add(new DEFactory.YResolutionDE(param.getYResolution())); // 283
      }
      ifd.add(new DEFactory.ResolutionUnitDE(Inch)); // 296

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStream os = baos;
      JPEGOutputStream jpegos = null;

      if (comp == JPEG) {
        jpegos = new JPEGOutputStream(baos);

        int quality = (param == null) ? 50 : (int) (param.getCompressionQuality() * 100);

        jpegos.setZZQuantizationTable(0, JPEGConstants.LQT, quality);
        jpegos.setZZQuantizationTable(1, JPEGConstants.CQT, quality);

        jpegos.setRawDCHuffmanTable(0, JPEGConstants.HLDCTable);
        jpegos.setRawACHuffmanTable(0, JPEGConstants.HLACTable);
        jpegos.setRawDCHuffmanTable(1, JPEGConstants.HCDCTable);
        jpegos.setRawACHuffmanTable(1, JPEGConstants.HCACTable);

        jpegos.defineQuantizationTables();
        jpegos.defineHuffmanTables();
        jpegos.close();

        DEFactory.JPEGTablesDE jpegtables = new DEFactory.JPEGTablesDE(baos.toByteArray());
        ifd.add(jpegtables); // 347

        baos.reset();

        os = jpegos;
      }

      //      CCIR Recommendation 601-1  LumaRed=299/1000 LumaGreen=587/1000 LumeBlue=114/1000
      //      Y  = ( LumaRed * R + LumaGreen * G + LumaBlue * B )
      //      Cb = ( B - Y ) / ( 2 - 2 * LumaBlue )
      //      Cr = ( R - Y ) / ( 2 - 2 * LumaRed )

      double LumaRed = 299.0 / 1000.0;
      double LumaGreen = 587.0 / 1000.0;
      double LumaBlue = 114.0 / 1000.0;

      DEFactory.YCbCrCoefficientsDE YCbCrCoeff = new DEFactory.YCbCrCoefficientsDE();
      YCbCrCoeff.setLumaRed(LumaRed); // Y
      YCbCrCoeff.setLumaGreen(LumaGreen); // Cb
      YCbCrCoeff.setLumaBlue(LumaBlue); // Cr
      ifd.add(YCbCrCoeff); // 529

      DEFactory.YCbCrSubSamplingDE YCbCrSubSampling = new DEFactory.YCbCrSubSamplingDE();
      YCbCrSubSampling.setHoriz(ssh);
      YCbCrSubSampling.setVert(ssv);
      ifd.add(YCbCrSubSampling); // 530

      double RfBY = 0;
      double RfWY = 255;
      double RfBCb = 128;
      double RfWCb = 255;
      double RfBCr = 128;
      double RfWCr = 255;

      DEFactory.ReferenceBlackWhiteDE ReferenceBlackWhite = new DEFactory.ReferenceBlackWhiteDE();
      ReferenceBlackWhite.setY(RfBY, RfWY);
      ReferenceBlackWhite.setCb(RfBCb, RfWCb);
      ReferenceBlackWhite.setCr(RfBCr, RfWCr);
      ifd.add(ReferenceBlackWhite); // 532

      TIFFYCbCrOutputStream ycbcros;
      if (jpegos == null) {
        ycbcros = new TIFFYCbCrOutputStream(os, width, ssv, ssh);
        os = new TIFFSubSamplingOutputStream(ycbcros, width, ssv, ssh);
      } else {
        ycbcros = new TIFFYCbCrOutputStream(os, width, 1, 1); // jpeg does own subsampling
        os = ycbcros;
      }

      ycbcros.setPositioning(1);
      ycbcros.setColourCoefficients(LumaRed, LumaGreen, LumaBlue);
      ycbcros.setRfBWY(RfBY, RfWY);
      ycbcros.setRfBWCb(RfBCb, RfWCb);
      ycbcros.setRfBWCr(RfBCr, RfWCr);

      WritableRaster raster = image.getRaster();
      DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer();
      int[] imgdata = (int[]) buffer.getData();

      int c = 0, index = 0;
      for (int y = 0; y < height; y += maxrps) {

        if ((height - y) < maxrps) {
          maxrps = height - y;
        }

        if (jpegos != null) {
          jpegos.startOfImage();
          int[] hv = {(ssh << 4) | ssv, 0x11, 0x11}; // (Hi<<4)|Vi
          int[] q = {0, 1, 1}; // quantization table Y=0, Cb=Cr=1
          //          jpegos.startOfFrame(((maxrps+ssv-1)/ssv)*ssv,ww,hv,q);
          jpegos.startOfFrame(maxrps, ww, hv, q);
          int[] sel = {0, 1, 1}; // DC,AC code table Y=0, Cb=Cr=1
          jpegos.startOfScan(sel);
        }

        for (int i = 0; i < maxrps; i++) {
          int x = 0;
          while (x < width) {
            c = imgdata[x + (y + i) * width];
            //            c = image.getRGB(x,y+i);
            os.write((c >> 16) & 0x000000FF);
            os.write((c >> 8) & 0x000000FF);
            os.write(c & 0x000000FF);
            x++;
          }
          while (x < ww) {
            os.write((c >> 16) & 0x000000FF);
            os.write((c >> 8) & 0x000000FF);
            os.write(c & 0x000000FF);
            x++;
          }
        }
        os.close();

        byte[] data = baos.toByteArray();
        counts.setCount(index, data.length); // update ifd strip counter array
        offsets.setOffset(index, out.getStreamPosition()); // update ifd image data offset array
        out.write(data); // write to image stream
        baos.reset();
        index++;
      }
      return ifd;
    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException(getClass().getName() + ".writeYCbCrImage:\n\t" + e.getMessage());
    }
  }