/**
   * Gets pixel data of an <code>IIOImage</code> object.
   *
   * @param image an <code>IIOImage</code> object
   * @return a byte buffer of pixel data
   * @throws Exception
   */
  public static ByteBuffer getImageByteBuffer(IIOImage image) throws IOException {
    // Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get tif writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

    if (writer == null) {
      throw new RuntimeException(
          "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
    }

    // Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(
        streamMetadata, new IIOImage(image.getRenderedImage(), null, null), tiffWriteParam);
    //        writer.write(image.getRenderedImage());
    writer.dispose();
    //        ImageIO.write(image.getRenderedImage(), "tiff", ios); // this can be used in lieu of
    // writer
    ios.seek(0);
    BufferedImage bi = ImageIO.read(ios);
    return convertImageData(bi);
  }
Esempio n. 2
0
  /**
   * Loads the tileset defined in the constructor into a JPanel which it then returns. Makes no
   * assumptions about height or width, which means it needs to read an extra 64 tiles at worst (32
   * down to check height and 32 across for width), since the maximum height/width is 32 tiles.
   */
  public JPanel loadTileset() {
    int height = MAX_TILESET_SIZE;
    int width = MAX_TILESET_SIZE;

    boolean maxHeight = false;
    boolean maxWidth = false;

    // find width
    int j = 0;
    while (!maxWidth) {
      try {
        File f = new File(tileDir + "/" + j + "_" + 0 + ".png");
        ImageIO.read(f);
      } catch (IOException e) {
        width = j;
        maxWidth = true;
      }
      j += TILE_SIZE;
    }

    // find height
    int i = 0;
    while (!maxHeight) {
      try {
        File f = new File(tileDir + "/" + 0 + "_" + i + ".png");
        ImageIO.read(f);
      } catch (IOException e) {
        height = i;
        maxHeight = true;
      }
      i += TILE_SIZE;
    }

    JPanel tileDisplay = new JPanel();
    tileDisplay.setLayout(new GridLayout(height / TILE_SIZE, width / TILE_SIZE));
    tileDisplay.setMinimumSize(new Dimension(width, height));
    tileDisplay.setPreferredSize(new Dimension(width, height));
    tileDisplay.setMaximumSize(new Dimension(width, height));

    for (i = 0; i < height; i += TILE_SIZE) {
      for (j = 0; j < width; j += TILE_SIZE) {
        String fPath = tileDir + "/" + j + "_" + i;
        try {
          int[] mov = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

          Image icon = getTile(tileDir, j, i, 1);
          Tile tile =
              new Tile(new ImageIcon(icon), "palette", 0, 0, mov, "none", false, "" + j + "_" + i);
          tile.addMouseListener(new PaletteButtonListener());
          tile.setMaximumSize(new Dimension(TILE_SIZE, TILE_SIZE));
          tile.setPreferredSize(new Dimension(TILE_SIZE, TILE_SIZE));
          tile.setMinimumSize(new Dimension(TILE_SIZE, TILE_SIZE));
          tileDisplay.add(tile);
        } catch (IOException e) {
        }
      }
    }
    return tileDisplay;
  }
  /**
   * Gets a list of <code>IIOImage</code> objects for an image file.
   *
   * @param imageFile input image file. It can be any of the supported formats, including TIFF,
   *     JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL Ghostscript is installed
   * @return a list of <code>IIOImage</code> objects
   * @throws Exception
   */
  public static List<IIOImage> getIIOImageList(File imageFile) throws IOException {
    File workingTiffFile = null;

    ImageReader reader = null;
    ImageInputStream iis = null;

    try {
      // convert PDF to TIFF
      if (imageFile.getName().toLowerCase().endsWith(".pdf")) {
        workingTiffFile = PdfUtilities.convertPdf2Tiff(imageFile);
        imageFile = workingTiffFile;
      }

      List<IIOImage> iioImageList = new ArrayList<IIOImage>();

      String imageFileName = imageFile.getName();
      String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);
      if (imageFormat.matches("(pbm|pgm|ppm)")) {
        imageFormat = "pnm";
      } else if (imageFormat.equals("jp2")) {
        imageFormat = "jpeg2000";
      }
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
      reader = readers.next();

      if (reader == null) {
        throw new RuntimeException(
            "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
      }

      iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);

      int imageTotal = reader.getNumImages(true);

      for (int i = 0; i < imageTotal; i++) {
        //                IIOImage oimage = new IIOImage(reader.read(i), null,
        // reader.getImageMetadata(i));
        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
        iioImageList.add(oimage);
      }

      return iioImageList;
    } finally {
      try {
        if (iis != null) {
          iis.close();
        }
        if (reader != null) {
          reader.dispose();
        }
      } catch (Exception e) {
        // ignore
      }
      if (workingTiffFile != null && workingTiffFile.exists()) {
        workingTiffFile.delete();
      }
    }
  }
Esempio n. 4
0
 /**
  * Takes a filepath to a tileset folder, x, y coordinates and a scale and returns the desired
  * tile.
  */
 public static Image getTile(String filepath, int x, int y, int scale) throws IOException {
   // System.out.println(filepath+"/"+x+"_"+y);
   try {
     return scaleImage(ImageIO.read(new File(filepath + "/" + x + "_" + y + ".png")), scale);
   } catch (IOException e) {
     return scaleImage(ImageIO.read(new File(filepath + "/" + x + "_" + y)), scale);
   }
 }
Esempio n. 5
0
 public void save(File file) throws IOException {
   if (file.getName().endsWith(".gif")) {
     ImageIO.write(_i, "png", file);
   } else if (file.getName().endsWith(".jpg")) {
     ImageIO.write(_i, "jpg", file);
   } else {
     if (!file.getName().endsWith(".png")) {
       file = new File(file.toString() + ".png");
     }
     ImageIO.write(_i, "png", file);
   }
 }
  /**
   * Creates a list of TIFF image files from an image file. It basically converts images of other
   * formats to TIFF format, or a multi-page TIFF image to multiple TIFF image files.
   *
   * @param imageFile input image file
   * @param index an index of the page; -1 means all pages, as in a multi-page TIFF image
   * @return a list of TIFF image files
   * @throws Exception
   */
  public static List<File> createTiffFiles(File imageFile, int index) throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    String imageFileName = imageFile.getName();
    String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);

    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
    ImageReader reader = readers.next();

    if (reader == null) {
      throw new RuntimeException(
          "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
    }

    ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
    reader.setInput(iis);
    // Read the stream metadata
    //        IIOMetadata streamMetadata = reader.getStreamMetadata();

    // Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get tif writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

    // Read the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    int imageTotal = reader.getNumImages(true);

    for (int i = 0; i < imageTotal; i++) {
      // all if index == -1; otherwise, only index-th
      if (index == -1 || i == index) {
        //                BufferedImage bi = reader.read(i);
        //                IIOImage oimage = new IIOImage(bi, null, reader.getImageMetadata(i));
        IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
        File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
        ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile);
        writer.setOutput(ios);
        writer.write(streamMetadata, oimage, tiffWriteParam);
        ios.close();
        tiffFiles.add(tiffFile);
      }
    }
    writer.dispose();
    reader.dispose();

    return tiffFiles;
  }
Esempio n. 7
0
  public void readImg(String in) {
    try {
      character = ImageIO.read(new File(in));
    } catch (IOException e) {

    }
  }
Esempio n. 8
0
 /**
  * Returns the specified image.
  *
  * @param url image url
  * @return image
  */
 public static Image get(final URL url) {
   try {
     return ImageIO.read(url);
   } catch (final IOException ex) {
     throw Util.notExpected(ex);
   }
 }
    public VideoTrack(PullSourceStream stream) throws ResourceUnavailableException {
      super();

      this.stream = stream;
      // set format

      // read first frame to determine format
      final Buffer buffer = new Buffer();
      readFrame(buffer);
      if (buffer.isDiscard() || buffer.isEOM())
        throw new ResourceUnavailableException("Unable to read first frame");
      // TODO: catch runtime exception too?

      // parse jpeg
      final java.awt.Image image;
      try {
        image =
            ImageIO.read(
                new ByteArrayInputStream(
                    (byte[]) buffer.getData(), buffer.getOffset(), buffer.getLength()));
      } catch (IOException e) {
        logger.log(Level.WARNING, "" + e, e);
        throw new ResourceUnavailableException("Error reading image: " + e);
      }

      if (image == null) {
        logger.log(Level.WARNING, "Failed to read image (ImageIO.read returned null).");
        throw new ResourceUnavailableException();
      }

      if (frameContentType.equals("image/jpeg"))
        format =
            new JPEGFormat(
                new Dimension(image.getWidth(null), image.getHeight(null)),
                Format.NOT_SPECIFIED,
                Format.byteArray,
                -1.f,
                Format.NOT_SPECIFIED,
                Format.NOT_SPECIFIED);
      else if (frameContentType.equals("image/gif"))
        format =
            new GIFFormat(
                new Dimension(image.getWidth(null), image.getHeight(null)),
                Format.NOT_SPECIFIED,
                Format.byteArray,
                -1.f);
      else if (frameContentType.equals("image/png"))
        format =
            new PNGFormat(
                new Dimension(image.getWidth(null), image.getHeight(null)),
                Format.NOT_SPECIFIED,
                Format.byteArray,
                -1.f);
      else
        throw new ResourceUnavailableException(
            "Unsupported frame content type: " + frameContentType);
      // TODO: this discards first image. save and return first time
      // readFrame is called.

    }
Esempio n. 10
0
 /*======== public void save() ==========
 Inputs:  String filename
 Returns:
 saves the bufferedImage as a png file with the given filename
 ====================*/
 public void save(String filename) {
   try {
     File fn = new File(filename);
     ImageIO.write(bi, "png", fn);
   } catch (IOException e) {
   }
 }
Esempio n. 11
0
 public void save(String filename, String type) {
   try {
     ImageIO.write(img, type, new File(filename + "." + type));
     System.out.println("Saving under " + filename + "." + type);
   } catch (Exception e) {
     System.out.println("Kann Datei " + filename + "." + type + " nicht anlegen");
   }
 }
  public static List<File> createTiffFiles(List<IIOImage> imageList, int index, int dpiX, int dpiY)
      throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    // Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get tif writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

    if (writer == null) {
      throw new RuntimeException(
          "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
    }

    // Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    // all if index == -1; otherwise, only index-th
    for (IIOImage oimage : (index == -1 ? imageList : imageList.subList(index, index + 1))) {
      if (dpiX != 0 && dpiY != 0) {
        // Get the default image metadata.
        ImageTypeSpecifier imageType =
            ImageTypeSpecifier.createFromRenderedImage(oimage.getRenderedImage());
        IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, null);
        imageMetadata = setDPIViaAPI(imageMetadata, dpiX, dpiY);
        oimage.setMetadata(imageMetadata);
      }

      File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
      ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile);
      writer.setOutput(ios);
      writer.write(streamMetadata, oimage, tiffWriteParam);
      ios.close();
      tiffFiles.add(tiffFile);
    }
    writer.dispose();

    return tiffFiles;
  }
Esempio n. 13
0
  public BufferedImage getImage(String Direct, String FName) {
    // JOptionPane.showMessageDialog(null, "GameCharacter");
    try {
      BufferedImage bg = ImageIO.read(getClass().getResource(Direct + FName));
      return bg;

    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, getClass().toString());
    }
    return null;
  }
Esempio n. 14
0
  /**
   * Loads an image from a given image identifier.
   *
   * @param imageID The identifier of the image.
   * @return The image for the given identifier.
   */
  public static ImageIcon getImage(String imageID) {
    BufferedImage image = null;

    String path = IMAGE_RESOURCE_BUNDLE.getString(imageID);

    try {
      image = ImageIO.read(Resources.class.getClassLoader().getResourceAsStream(path));
    } catch (IOException e) {
      log.error("Failed to load image:" + path, e);
    }

    return new ImageIcon(image);
  }
Esempio n. 15
0
  // we define the method for downloading when pressing on the download button
  public void qrvidlink() {
    try {
      System.setSecurityManager(new SecurityManager());

      ipadd = tfIP.getText();
      Interface client = (Interface) Naming.lookup("rmi://" + ipadd + "/getvid");

      // Get the String entered into the TextField tfInput, convert to int
      link = tfInput.getText();
      vlink = client.getvid(link);

      // here we receive the image serialized into bytes from the server and
      // saved it on the client as png image
      byte[] bytimg = client.qrvid(vlink);
      BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytimg));
      File outputfile = new File("qrcode.png");
      ImageIO.write(img, "png", outputfile);

      // img= new ImageIcon(bytimg.toByteArray());
    } catch (Exception e) {
      System.out.println("[System] Server failed: " + e);
    }
  }
  /**
   * Merges multiple images into one TIFF image.
   *
   * @param inputImages an array of image files
   * @param outputTiff the output TIFF file
   * @throws Exception
   */
  public static void mergeTiff(File[] inputImages, File outputTiff) throws IOException {
    List<IIOImage> imageList = new ArrayList<IIOImage>();

    for (int i = 0; i < inputImages.length; i++) {
      imageList.addAll(getIIOImageList(inputImages[i]));
    }

    if (imageList.isEmpty()) {
      // if no image
      return;
    }

    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    ImageWriter writer = writers.next();

    // Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    ImageOutputStream ios = ImageIO.createImageOutputStream(outputTiff);
    writer.setOutput(ios);

    IIOImage firstIioImage = imageList.remove(0);
    writer.write(streamMetadata, firstIioImage, tiffWriteParam);

    int i = 1;
    for (IIOImage iioImage : imageList) {
      writer.writeInsert(i++, iioImage, tiffWriteParam);
    }
    ios.close();

    writer.dispose();
  }
Esempio n. 17
0
  /**
   * Writes this map to a JPG file.
   *
   * @param filename the path and name of the file to create.
   */
  public void writeToJPGFile(String filename) throws IOException {

    this.prepareToDraw();

    BufferedImage buffImage =
        new BufferedImage(p.getWidth(), p.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = buffImage.createGraphics();
    try {
      p.draw(graphics2D);
      System.out.println("Writing picture to " + filename);
      ImageIO.write(buffImage, "JPG", new File(filename));
    } finally {
      graphics2D.dispose();
    }
  }
  /** A static method for initialing all the images associated with this widget */
  private static void loadImages() {
    // Already in cache, save us from file IO time.
    if (frames != null) {
      return;
    }

    // Okay, it's not in cache, load the images.
    try {
      frames = new ArrayList<BufferedImage>();
      for (int i = 0; i < 2; i++) {
        frames.add(fixTransparency(ImageIO.read(new File(IMAGE_PREFIX + (i + 1) + ".png"))));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 19
0
  public void write() {
    System.out.println("Writing image");
    BufferedImage img = new BufferedImage(1600, 1200, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();

    g.setColor(Color.white);
    g.fillRect(0, 0, 1600, 1200);
    g.setColor(Color.black);
    counts = new double[depth];
    for (int i = 0; i < depth; i++) {
      counts[i] = 0;
    }
    draw(root, g, 800, 10);

    try {
      File f = new File(jpeg);
      ImageIO.write((RenderedImage) img, "jpeg", f);
    } catch (Exception e) {
      System.out.println("Error writing image data");
    }
  }
Esempio n. 20
0
  // Takes a PImage and compresses it into a JPEG byte stream
  // Adapted from Dan Shiffman's UDP Sender code
  public byte[] compressImage(PImage img) {
    // We need a buffered image to do the JPG encoding
    BufferedImage bimg = new BufferedImage(img.width, img.height, BufferedImage.TYPE_INT_RGB);

    img.loadPixels();
    bimg.setRGB(0, 0, img.width, img.height, img.pixels, 0, img.width);

    // Need these output streams to get image as bytes for UDP communication
    ByteArrayOutputStream baStream = new ByteArrayOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(baStream);

    // Turn the BufferedImage into a JPG and put it in the BufferedOutputStream
    // Requires try/catch
    try {
      ImageIO.write(bimg, "jpg", bos);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Get the byte array, which we will send out via UDP!
    return baStream.toByteArray();
  }
 private void writeToFile(File selectedFile, ImageWriterSpiFileFilter ff) {
   try {
     ImageOutputStream ios = ImageIO.createImageOutputStream(selectedFile);
     ImageWriter iw = ff.getImageWriterSpi().createWriterInstance();
     iw.setOutput(ios);
     ImageWriteParam iwp = iw.getDefaultWriteParam();
     if (iwp.canWriteCompressed()) {
       iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
       // set maximum image quality
       iwp.setCompressionQuality(1.f);
     }
     Image image = viewerPanel.getImage();
     BufferedImage bufferedImage;
     if (viewerPanel.getImage() instanceof BufferedImage)
       bufferedImage = (BufferedImage) viewerPanel.getImage();
     else {
       bufferedImage =
           new BufferedImage(
               image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
       bufferedImage.createGraphics().drawImage(image, 0, 0, null);
     }
     iw.write(null, new IIOImage(bufferedImage, null, null), iwp);
     iw.dispose();
     ios.close();
   } catch (IOException ioe) {
     JOptionPane.showMessageDialog(
         viewerPanel,
         messagesBundle.getString(
             "ImageViewerPanelSaveAction." + "Error_during_image_saving_message_7"),
         //$NON-NLS-1$
         messagesBundle.getString("ImageViewerPanelSaveAction." + "Error_dialog_title_8"),
         //$NON-NLS-1$
         JOptionPane.ERROR_MESSAGE);
     ioe.printStackTrace();
   }
 }
  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);
  }
  // Constructor connection receiving a socket number
  public ClientGUI(String host, int port, int udpPort) {

    super("Clash of Clans");
    defaultPort = port;
    defaultUDPPort = udpPort;
    defaultHost = host;

    // the server name and the port number
    JPanel serverAndPort = new JPanel(new GridLayout(1, 5, 1, 3));
    tfServer = new JTextField(host);
    tfPort = new JTextField("" + port);
    tfPort.setHorizontalAlignment(SwingConstants.RIGHT);

    // CHAT COMPONENTS
    chatStatus = new JLabel("Please login first", SwingConstants.LEFT);
    chatField = new JTextField(18);
    chatField.setBackground(Color.WHITE);

    JPanel chatControls = new JPanel();
    chatControls.add(chatStatus);
    chatControls.add(chatField);
    chatControls.setBounds(0, 0, 200, 50);

    chatArea = new JTextArea("Welcome to the Chat room\n", 80, 80);
    chatArea.setEditable(false);
    JScrollPane jsp = new JScrollPane(chatArea);
    jsp.setBounds(0, 50, 200, 550);

    JPanel chatPanel = new JPanel(null);
    chatPanel.setSize(1000, 600);
    chatPanel.add(chatControls);
    chatPanel.add(jsp);

    // LOGIN COMPONENTS
    mainLogin = new MainPanel();
    mainLogin.add(new JLabel("Main Login"));

    usernameField = new JTextField("user", 15);
    passwordField = new JTextField("password", 15);
    login = new CButton("Login");
    login.addActionListener(this);

    sideLogin = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    sideLogin.add(usernameField);
    sideLogin.add(passwordField);
    sideLogin.add(login);

    // MAIN MENU COMPONENTS
    mainMenu = new MainPanel();
    mmLabel = new JLabel("Main Menu");
    timer = new javax.swing.Timer(1000, this);
    mainMenu.add(mmLabel);

    sideMenu = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    cmButton = new CButton("Customize Map");
    tmButton = new CButton("Troop Movement");
    gsButton = new CButton("Game Start");
    logout = new CButton("Logout");
    cmButton.addActionListener(this);
    tmButton.addActionListener(this);
    gsButton.addActionListener(this);
    logout.addActionListener(this);
    sideMenu.add(cmButton);
    // sideMenu.add(tmButton);
    sideMenu.add(gsButton);
    sideMenu.add(logout);

    // CM COMPONENTS
    mainCM = new MainPanel(new GridLayout(mapSize, mapSize));
    tiles = new Tile[mapSize][mapSize];
    int tileSize = mainCM.getWidth() / mapSize;
    for (int i = 0; i < mapSize; i++) {
      tiles[i] = new Tile[mapSize];
      for (int j = 0; j < mapSize; j++) {
        tiles[i][j] = new Tile(i, j);
        tiles[i][j].setPreferredSize(new Dimension(tileSize, tileSize));
        tiles[i][j].setSize(tileSize, tileSize);
        tiles[i][j].addActionListener(this);

        if ((i + j) % 2 == 0) tiles[i][j].setBackground(new Color(102, 255, 51));
        else tiles[i][j].setBackground(new Color(51, 204, 51));

        mainCM.add(tiles[i][j]);
      }
    }

    sideCM = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    cmBack = new CButton("Main Menu");
    cmBack.setSize(150, 30);
    cmBack.setPreferredSize(new Dimension(150, 30));
    cmBack.addActionListener(this);
    sideCM.add(cmBack);

    // TM COMPONENTS
    mainTM = new MainPanel(null);
    mapTM = new Map(600);
    mapTM.setPreferredSize(new Dimension(600, 600));
    mapTM.setSize(600, 600);
    mapTM.setBounds(0, 0, 600, 600);
    mainTM.add(mapTM);

    sideTM = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    tmBack = new CButton("Main Menu");
    tmBack.setSize(150, 30);
    tmBack.setPreferredSize(new Dimension(150, 30));
    tmBack.addActionListener(this);
    sideTM.add(tmBack);

    JRadioButton button;
    ButtonGroup group;

    ub = new ArrayList<JRadioButton>();
    group = new ButtonGroup();

    button = new JRadioButton("Barbarian");
    button.addActionListener(this);
    ub.add(button);
    sideTM.add(button);
    group.add(button);

    button = new JRadioButton("Archer");
    button.addActionListener(this);
    ub.add(button);
    sideTM.add(button);
    group.add(button);

    createBuildings();
    bb = new ArrayList<JRadioButton>();

    group = new ButtonGroup();

    JRadioButton removeButton = new JRadioButton("Remove Building");
    bb.add(removeButton);
    sideCM.add(removeButton);
    group.add(removeButton);

    for (int i = 0; i < bList.size(); i++) {
      button = new JRadioButton(bList.get(i).getName() + '-' + bList.get(i).getQuantity());
      bb.add(button);
      sideCM.add(button);
      group.add(button);
    }

    mainPanels = new MainPanel(new CardLayout());
    mainPanels.add(mainLogin, "Login");
    mainPanels.add(mainMenu, "Menu");
    mainPanels.add(mainCM, "CM");
    mainPanels.add(mainTM, "TM");

    sidePanels = new SidePanel(new CardLayout());
    sidePanels.add(sideLogin, "Login");
    sidePanels.add(sideMenu, "Menu");
    sidePanels.add(sideCM, "CM");
    sidePanels.add(sideTM, "TM");

    JPanel mainPanel = new JPanel(null);
    mainPanel.setSize(1000, 600);
    mainPanel.add(sidePanels);
    mainPanel.add(mainPanels);
    mainPanel.add(chatPanel);

    add(mainPanel, BorderLayout.CENTER);

    try {
      setIconImage(ImageIO.read(new File("images/logo.png")));
    } catch (IOException exc) {
      exc.printStackTrace();
    }

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(1000, 600);
    setVisible(true);
    setResizable(false);
    chatField.requestFocus();
  }
Esempio n. 24
0
  // Thread's run method aimed at creating a bitmap asynchronously
  public void run() {
    Drawing drawing = new Drawing();
    PicText rawPicText = new PicText();
    String s = ((PicText) element).getText();
    rawPicText.setText(s);
    drawing.add(
        rawPicText); // bug fix: we must add a CLONE of the PicText, otherwise it loses it former
                     // parent... (then pb with the view )
    drawing.setNotparsedCommands(
        "\\newlength{\\jpicwidth}\\settowidth{\\jpicwidth}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicheight}\\settoheight{\\jpicheight}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicdepth}\\settodepth{\\jpicdepth}{"
            + s
            + "}"
            + CR_LF
            + "\\typeout{JPICEDT INFO: \\the\\jpicwidth, \\the\\jpicheight,  \\the\\jpicdepth }"
            + CR_LF);
    RunExternalCommand.Command commandToRun = RunExternalCommand.Command.BITMAP_CREATION;
    // RunExternalCommand command = new RunExternalCommand(drawing, contentType,commandToRun);
    boolean isWriteTmpTeXfile = true;
    String bitmapExt = "png"; // [pending] preferences
    String cmdLine =
        "{i}/unix/tetex/create_bitmap.sh {p} {f} "
            + bitmapExt
            + " "
            + fileDPI; // [pending] preferences
    ContentType contentType = getContainer().getContentType();
    RunExternalCommand.isGUI = false; // System.out, no dialog box // [pending] debug
    RunExternalCommand command =
        new RunExternalCommand(drawing, contentType, cmdLine, isWriteTmpTeXfile);
    command
        .run(); // synchronous in an async. thread => it's ok (anyway, we must way until the LaTeX
                // process has completed)

    if (wantToComputeLatexDimensions) {
      // load size of text:
      try {
        File logFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + ".log");
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(logFile));
        } catch (FileNotFoundException fnfe) {
          System.out.println("Cannot find log file! " + fnfe.getMessage());
          System.out.println(logFile);
        } catch (IOException ioex) {
          System.out.println("Log file IO exception");
          ioex.printStackTrace();
        } // utile ?
        System.out.println("Log file created! file=" + logFile);
        getDimensionsFromLogFile(reader, (PicText) element);
        syncStringLocation(); // update dimensions
        syncBounds();
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that dimensions are available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    if (wantToGetBitMap) {
      // load image:
      try {
        File bitmapFile =
            new File(command.getTmpPath(), command.getTmpFilePrefix() + "." + bitmapExt);
        this.image = ImageIO.read(bitmapFile);
        System.out.println(
            "Bitmap created! file="
                + bitmapFile
                + ", width="
                + image.getWidth()
                + "pixels, height="
                + image.getHeight()
                + "pixels");
        if (image == null) return;
        syncStringLocation(); // sets strx, stry, and dimensions of text
        syncBounds();
        // update the AffineTransform that will be applied to the bitmap before displaying on screen
        PicText te = (PicText) element;
        text2ModelTr.setToIdentity(); // reset
        PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
        text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR !
        text2ModelTr.translate(te.getLeftX(), te.getTopY());
        text2ModelTr.scale(
            te.getWidth() / image.getWidth(),
            -(te.getHeight() + te.getDepth()) / image.getHeight());
        // [pending]  should do something special to avoid dividing by 0 or setting a rescaling
        // factor to 0 [non invertible matrix] (java will throw an exception)
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that bitmap is available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Esempio n. 25
0
  /**
   * Constructor to create a character
   *
   * @param x X Position
   * @param y Y Position
   * @param w Width of Image
   * @param h Height of Image
   * @param FileN Name of image file
   * @param S Max number of frames
   */
  public GameCharacter(
      double x, double y, double w, double h, String FileN, int S, int Ty, String c) {
    // Set position and size
    X = x;
    Y = y;
    W = w;
    H = h;

    BASIC_PROCESS = new ProgressBar(new Font("Arial", 36, 36), this);
    BASIC_EFFECTS = new ProgressBar(new Font("Arial", 36, 36), this);
    // Add magic attacks
    // Fireball
    for (int i = 0; i < FIREBALL.length; i++) {
      FIREBALL[i] = new MagicAttack(-500, -500, 39, 41, "Fireball.png", 3, 1, 2, "Fireball");
      FIREBALL[i].STATS.setStats(new String[] {"Damage=10", "Points=10"});
      FIREBALL[i].CASTER = this;
    }
    // Shock
    for (int i = 0; i < SHOCK.length; i++) {
      SHOCK[i] = new MagicAttack(-500, -500, 39, 41, "Shock.png", 2, 1, 0, "Shock");
      SHOCK[i].STATS.setStats(new String[] {"Damage=20", "Points=15"});
      SHOCK[i].CASTER = this;
    }
    // Darkness
    for (int i = 0; i < DARKNESS.length; i++) {
      DARKNESS[i] = new MagicAttack(-500, -500, 165, 164, "Darkness.png", 3, 1, 2, "Darkness");
      DARKNESS[i].STATS.setStats(new String[] {"Damage=100", "Points=50"});
      DARKNESS[i].CASTER = this;
    }
    // Life Drain
    for (int i = 0; i < LIFE_DRAIN.length; i++) {
      LIFE_DRAIN[i] = new MagicAttack(-500, -500, 32, 32, "Life Drain.png", 7, 1, 0, "Life Drain");
      LIFE_DRAIN[i].STATS.setStats(new String[] {"Damage=50", "Points=25"});
      LIFE_DRAIN[i].CASTER = this;
    }
    // Get Image
    try {

      if (isJar()) {
        // Character
        imgCHARAC = getImage("/Graphics/Character/", FileN);

        // Blood
        int BloodType = (int) Math.round(Math.random() * 3) + 1;
        imgBLOOD = getImage("/Graphics/Effects/", "Dead" + BloodType + ".png");

        // Quest
        imgQStart = getImage("/Graphics/Effects/", "Quest_Start.png");
        imgQEnd = getImage("/Graphics/Effects/", "Quest_Complete.png");

      } else {
        // Character
        imgCHARAC = ImageIO.read(Paths.get(DIRECT + FileN).toFile());

        // Blood
        int BloodType = (int) Math.round(Math.random() * 3) + 1;
        imgBLOOD = ImageIO.read(Paths.get(DIRECT2 + "Dead" + BloodType + ".png").toFile());

        // Quest
        imgQStart = ImageIO.read(Paths.get(DIRECT2 + "Quest_Start.png").toFile());
        imgQEnd = ImageIO.read(Paths.get(DIRECT2 + "Quest_Complete.png").toFile());
      }

    } catch (Exception e) {
    }

    // Max number of frames
    SIZE = S;

    // Sprite type
    TYPE = Ty;

    // Assign class
    CLASS = c;
    Cl = c;

    // Add items and attacks according to class
    if (CLASS.equals("Player")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Rusted Dagger",
          20,
          1,
          "Dagger_4.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem(
          "Wooden Staff",
          20,
          1,
          "Staff_1.png",
          "Meele",
          new String[] {"Damage=5", "Attack Speed=1"});

      // Equip items
      INVENTORY.ItemEffect(1, this);
      // MEELE_WEAPON=null;
      // Assign Magic
      SPELL_LIST.add(FIREBALL);

      // Inventory type
      INVENTORY.Type = "Player";
    } else if (CLASS.equals("Citizen")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Ai
      NAI = new NPCAI(this);

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 15 + 5);

      INVENTORY.Type = "Friendly";
    } else if (CLASS.equals("Blacksmith")) {

      // Add items
      INVENTORY.addItem(
          "Silver Dagger",
          250,
          1,
          "Dagger_3.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem(
          "Steel Dagger",
          450,
          1,
          "Dagger_5.png",
          "Meele",
          new String[] {"Damage=35", "Attack Speed=1"});
      // INVENTORY.addItem("Assassin blade", 750,1, "Dagger_6.png","Meele",new
      // String[]{"Damage=45","Attack Speed=1"});
      // INVENTORY.addItem("Serpent Dagger", 5000,1, "Dagger_2.png","Meele",new
      // String[]{"Damage=50","Attack Speed=1"});
      // INVENTORY.addItem("Dagger of Time", 5050,1, "Dagger_1.png","Meele",new
      // String[]{"Damage=75","Attack Speed=1"});

      INVENTORY.addItem(
          "Steel Sword",
          450,
          1,
          "Sword_1.png",
          "Meele",
          new String[] {"Damage=30", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Iron Sword",
          50,
          1,
          "Sword_2.png",
          "Meele",
          new String[] {"Damage=15", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Silver Sword",
          100,
          1,
          "Sword_5.png",
          "Meele",
          new String[] {"Damage=20", "Attack Speed=0.5"});
      // INVENTORY.addItem("Iron Scimitar", 150,1, "Sword_7.png","Meele",new
      // String[]{"Damage=15","Attack Speed=0.75"});
      // INVENTORY.addItem("Steel Scimitar", 500,1, "Sword_4.png","Meele",new
      // String[]{"Damage=50","Attack Speed=0.75"});
      // INVENTORY.addItem("Steel Katana", 450,1, "Sword_6.png","Meele",new
      // String[]{"Damage=40","Attack Speed=0.95"});
      // INVENTORY.addItem("Butcher's Sword", 5000,1, "Sword_3.png","Meele",new
      // String[]{"Damage=100","Attack Speed=0.55"});
      // INVENTORY.addItem("Blood Thirster", 6000,1, "Sword_8.png","Meele",new
      // String[]{"Damage=200","Attack Speed=0.75"});

      INVENTORY.addItem(
          "Iron Hammer",
          150,
          1,
          "Hammer_1.png",
          "Meele",
          new String[] {"Damage=40", "Attack Speed=0.15"});
      // INVENTORY.addItem("Steel Hammer", 450,1, "Hammer_0.png","Meele",new
      // String[]{"Damage=60","Attack Speed=0.15"});
      // INVENTORY.addItem("Iron Mace", 50,1, "Mace_1.png","Meele",new String[]{"Damage=15","Attack
      // Speed=0.5"});

      INVENTORY.addItem("Steel Helmet", 250, 1, "Head_1.png", "H_armor", new String[] {"Armor=20"});
      INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"});
      // INVENTORY.addItem("Iron Horn Helmet", 350,1, "Head_6.png","H_armor",new
      // String[]{"Armor=50","Magic Resist=0"});
      // INVENTORY.addItem("Steel Horn Helmet", 500,1, "Head_7.png","H_armor",new
      // String[]{"Armor=80","Magic Resist=0"});
      // INVENTORY.addItem("Skysteel Helmet", 4000,1, "Head_4.png","H_armor",new
      // String[]{"Armor=60","Magic Resist=25"});

      INVENTORY.addItem(
          "Iron Cuirass", 250, 1, "Chest_4.png", "C_armor", new String[] {"Armor=20"});
      INVENTORY.addItem(
          "Steel Cuirass", 350, 1, "Chest_1.png", "C_armor", new String[] {"Armor=30"});
      // INVENTORY.addItem("Scale Cuirass", 550,1, "Chest_3.png","C_armor",new
      // String[]{"Armor=50"});
      // INVENTORY.addItem("Dark metal Cuirass", 750,1, "Chest_6.png","C_armor",new
      // String[]{"Armor=70"});
      // INVENTORY.addItem("Master Cuirass", 3050,1, "Chest_5.png","C_armor",new
      // String[]{"Armor=80","Magic Resist=25"});
      // INVENTORY.addItem("Legendary Cuirass", 3050,1, "Chest_2.png","C_armor",new
      // String[]{"Armor=100","Magic Resist=100"});

      INVENTORY.addItem(
          "Wooden Shield",
          50,
          1,
          "Shield_1.png",
          "Shield",
          new String[] {"Armor=5", "Magic Resist=0"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";

      // Set Stats
      STATS.setStats(new String[] {"Level = 5 "});
      MAX_HEALTH = 200;
      HEALTH = (int) MAX_HEALTH;
    } else if (CLASS.equals("Alchemist")) {
      // Add Items
      INVENTORY.addItem(
          "Health Potion", 25, 50, "Health Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Mana Potion", 20, 50, "Mana Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Speed Potion", 10, 50, "Speed Pot.png", "Potion", new String[] {"Points=5"});
      // INVENTORY.addItem("Invisib Potion", 50, 10, "Invisibility Pot.png","Potion",new
      // String[]{"Points=5"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";
    } else if (CLASS.equals("Inn Keeper")) {
      // Add Items
      INVENTORY.addItem("Roasted Fish", 15, 10, "Fish.png", "Food", new String[] {"Points=5"});
      INVENTORY.addItem("Apple", 15, 10, "Apple.png", "Food", new String[] {"Points=2"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";
    } else if (CLASS.equals("Mage")) {

      INVENTORY.addItem(
          "Leather Cap",
          250,
          1,
          "Head_8.png",
          "H_armor",
          new String[] {"Armor=5", "Magic Resist=25"});
      INVENTORY.addItem(
          "Dark Leather Cap",
          300,
          1,
          "Head_9.png",
          "H_armor",
          new String[] {"Armor=5", "Magic Resist=50"});
      // INVENTORY.addItem("Jesters Cap", 500,1, "Head_5.png","H_armor",new
      // String[]{"Armor=10","Magic Resist=90"});
      // INVENTORY.addItem("Skull Helmet", 5000,1, "Head_3.png","H_armor",new
      // String[]{"Armor=100","Magic Resist=100"});
      INVENTORY.addItem(
          "Shock Spell Stone",
          250,
          1,
          "Stone_1.png",
          "SpellStoner",
          new String[] {"Damage=" + SHOCK[0].STATS.DAMAGE});
      // INVENTORY.addItem("Darkness Spell Stone", 500,1, "Stone_1.png","SpellStoner",new
      // String[]{"Damage="+DARKNESS[0].STATS.DAMAGE});
      INVENTORY.addItem(
          "Life Drain Spell Stone",
          300,
          1,
          "Stone_1.png",
          "SpellStoner",
          new String[] {"Damage=" + LIFE_DRAIN[0].STATS.DAMAGE});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";

    } else if (CLASS.equals("Skeleton")) {

      // Add items
      INVENTORY.addItem(
          "Bone Club", 5, 1, "Mace_2.png", "Meele", new String[] {"Damage=5", "Attack Speed=1"});

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 10 + 2);

      // Use Item
      INVENTORY.ItemEffect(0, this);

      // Add AI
      EAI = new EnemyAI(this);
    } else if (CLASS.equals("Skeleton Chieftan")) {

      // Add Item
      INVENTORY.addItem(
          "Iron Sword",
          50,
          1,
          "Sword_2.png",
          "Meele",
          new String[] {"Damage=15", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 50 + 25);

      // Use Item
      INVENTORY.ItemEffect(0, this);

      // Assign Stats
      STATS.LEVEL = 3;
      HEALTH = 250;
      MAX_HEALTH = 250;

      // Opify
      Opify(1 / 1.25);

      // Add AI
      EAI = new EnemyAI(this);
    } else if (CLASS.equals("Shaman")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Ai
      NAI = new NPCAI(this);

    } else if (CLASS.equals("Dark Elf")) {

      // Add items
      INVENTORY.addItem(
          "Rusted Dagger",
          20,
          1,
          "Dagger_4.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"});

      // Assign Stats
      STATS.LEVEL = 2;
      HEALTH = 150;
      MAX_HEALTH = 150;

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 15 + 2);

      // Use Item
      INVENTORY.ItemEffect(0, this);
      INVENTORY.ItemEffect(1, this);

      // Add Ai
      EAI = new EnemyAI(this);

    } else if (CLASS.equals("Prisoner")) {
      INVENTORY.addItem("Key", 0, 1, "Key.png", "Key", new String[] {});
      // NAI= new NPCAI(this);
    }
  }
Esempio n. 26
0
  /**
   * Creates an instance of <tt>ShowPreviewDialog</tt>
   *
   * @param chatPanel The <tt>ChatConversationPanel</tt> that is associated with this dialog.
   */
  ShowPreviewDialog(final ChatConversationPanel chatPanel) {
    this.chatPanel = chatPanel;

    this.setTitle(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_DIALOG_TITLE"));
    okButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.OK"));
    cancelButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.CANCEL"));

    JPanel mainPanel = new TransparentPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    // mainPanel.setPreferredSize(new Dimension(200, 150));
    this.getContentPane().add(mainPanel);

    JTextPane descriptionMsg = new JTextPane();
    descriptionMsg.setEditable(false);
    descriptionMsg.setOpaque(false);
    descriptionMsg.setText(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_WARNING_DESCRIPTION"));

    Icon warningIcon = null;
    try {
      warningIcon =
          new ImageIcon(
              ImageIO.read(
                  GuiActivator.getResources().getImageURL("service.gui.icons.WARNING_ICON")));
    } catch (IOException e) {
      logger.debug("failed to load the warning icon");
    }
    JLabel warningSign = new JLabel(warningIcon);

    JPanel warningPanel = new TransparentPanel();
    warningPanel.setLayout(new BoxLayout(warningPanel, BoxLayout.X_AXIS));
    warningPanel.add(warningSign);
    warningPanel.add(Box.createHorizontalStrut(10));
    warningPanel.add(descriptionMsg);

    enableReplacement =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_STATUS"));
    enableReplacement.setOpaque(false);
    enableReplacement.setSelected(cfg.getBoolean(ReplacementProperty.REPLACEMENT_ENABLE, true));
    enableReplacementProposal =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_PROPOSAL"));
    enableReplacementProposal.setOpaque(false);

    JPanel checkBoxPanel = new TransparentPanel();
    checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.Y_AXIS));
    checkBoxPanel.add(enableReplacement);
    checkBoxPanel.add(enableReplacementProposal);

    JPanel buttonsPanel = new TransparentPanel(new FlowLayout(FlowLayout.CENTER));
    buttonsPanel.add(okButton);
    buttonsPanel.add(cancelButton);

    mainPanel.add(warningPanel);
    mainPanel.add(Box.createVerticalStrut(10));
    mainPanel.add(checkBoxPanel);
    mainPanel.add(buttonsPanel);

    okButton.addActionListener(this);
    cancelButton.addActionListener(this);

    this.setPreferredSize(new Dimension(390, 230));
  }
Esempio n. 27
0
 public static CA load(String file) throws IOException {
   BufferedImage i = ImageIO.read(new java.io.File(file));
   CA c = new CA(i);
   return c;
 }
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
Esempio n. 29
0
  protected void filePNG() {

    JFileChooser chooser = null;
    File pngFile = null;
    if (currentFile == null) {
      chooser = new JFileChooser(startDirectory);
    } else {
      pngFile = new File(currentFile.getName() + ".png");
      chooser = new JFileChooser(pngFile);
      if (!currentFile.isDirectory()) {
        chooser.setSelectedFile(currentFile);
      }
    }

    if (pngFile == null) return;
    try {
      BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
      paint(image.getGraphics());
      ImageIO.write(image, "png", pngFile);
    } catch (Exception e) {
    }
    return;
    /*		JFileChooser chooser = null;
    		File pngFile = null;
    		if (currentFile == null) {
    			chooser = new JFileChooser(startDirectory);
    		} else {
    			pngFile = new File(currentFile.getName()+".png");
    			chooser = new JFileChooser(pngFile);
    			if (!currentFile.isDirectory()) {
    				chooser.setSelectedFile(currentFile);
    			}
    		}
    		int returnVal = chooser.showSaveDialog(gw);
    		if (returnVal == JFileChooser.APPROVE_OPTION) {
    			File pngFile = chooser.getSelectedFile();

    			int maxX = Integer.MIN_VALUE;
    			int minX = Integer.MAX_VALUE;
    			int maxY = Integer.MIN_VALUE;
    			int minY = Integer.MAX_VALUE;

    			while(Node node : getNodes()) {
    				if(node.getX() > maxX) {
    					maxX = node.getX();
    				}
    				if(node.getX() < minX) {
    					minX = node.getX();
    				}
    				if(node.getY() > maxY) {
    					maxY = node.getY();
    				}
    				if(node.getY() < minY) {
    					minY = node.getY();
    				}
    			}

    			BufferedImage image = new BufferedImage(maxX-minX+50,maxY-minY+50,BufferedImage.TYPE_INT_RGB);



    			ImageIO.write(image,"png",pngFile);
    		}
    */ }
Esempio n. 30
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("image/jpeg");
      pageContext =
          _jspxFactory.getPageContext(
              this, request, response, "/myhtml/errorpage/erroe.jsp", true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("\r\n");
      out.write('\r');
      out.write('\n');

      // 设置页面不缓存
      response.setHeader("Pragma", "No-cache");
      response.setHeader("Cache-Control", "no-cache");
      response.setDateHeader("Expires", 0);

      //   在内存中创建图象
      int width = 60, height = 20;
      BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

      //   获取图形上下文
      Graphics g = image.getGraphics();

      // 生成随机类
      Random random = new Random();

      //   设定背景色
      g.setColor(getRandColor(200, 250));
      g.fillRect(0, 0, width, height);

      // 设定字体
      g.setFont(new Font("Times   New   Roman", Font.PLAIN, 18));

      // 画边框
      // g.setColor(new   Color());
      // g.drawRect(0,0,width-1,height-1);

      //   随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
      g.setColor(getRandColor(160, 200));
      for (int i = 0; i < 155; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        g.drawLine(x, y, x + xl, y + yl);
      }

      //   取随机产生的认证码(4位数字)
      String sRand = "";
      for (int i = 0; i < 4; i++) {
        String rand = String.valueOf(random.nextInt(10));
        sRand += rand;
        //   将认证码显示到图象中
        g.setColor(
            new Color(
                20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        // 调用函数出来的颜色相同,可能是å›
        // ä¸ºç§å­å¤ªæŽ¥è¿‘,所以只能直接生成
        g.drawString(rand, 13 * i + 6, 16);
      }

      //   将认证码存入SESSION
      session.setAttribute("rand", sRand);

      //   图象生效
      g.dispose();

      //   输出图象到页面
      ImageIO.write(image, "JPEG", response.getOutputStream());
      out.clear();
      out = pageContext.pushBody();

    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            out.clearBuffer();
          } catch (java.io.IOException e) {
          }
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else log(t.getMessage(), t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }