Ejemplo n.º 1
0
  /**
   * Creates an image from a word. The file is saved in the location specified by TEMP_IMAGE_PATH.
   *
   * @param subString The text.
   * @return An input stream.
   */
  private File createImage(String subString)
      throws FileNotFoundException, IOException, FontFormatException {

    // Create file
    File imageFile = File.createTempFile(getClass().getName(), "png");
    imageFile.createNewFile();

    // create the image
    // due to kerning problems, the image is being created 4 times to big
    // then being scaled down to the right size
    Text2PngFactory tpf = new Text2PngFactory();
    tpf.setFontFace(this.textFontFace);
    tpf.setFontSize((int) (this.textFontSize * SCALE_FACTOR));
    int[] textRGB = this.convertHexToRGB(this.textFontColor);
    int[] backRGB = this.convertHexToRGB(this.textBackColor);
    tpf.setTextRGB(textRGB[0], textRGB[1], textRGB[2]);
    tpf.setBackgroundRGB(backRGB[0], backRGB[1], backRGB[2]);
    tpf.setText(subString);

    BufferedImage bigImgBuff = (BufferedImage) tpf.createImage();
    if (SCALE_FACTOR != 1) {
      BufferedImage smallImgBuff = this.scaleImage(bigImgBuff, (1.0 / SCALE_FACTOR));
      ImageIO.write(smallImgBuff, "png", imageFile);
      smallImgBuff = null;
    } else {
      ImageIO.write(bigImgBuff, "png", imageFile);
    }
    bigImgBuff = null;
    return imageFile;
  }
Ejemplo n.º 2
0
  public void writeImageToStream(OutputStream os, String fileName, BufferedImage img) {
    // if we get here we need to save the image from the memory
    try {
      // try to write image using the format of the filename extension
      int pos = fileName.lastIndexOf('.');
      String ext = fileName.substring(pos + 1).toLowerCase(Locale.US);
      if (ext.equals("jpg") || ext.equals("jpeg")) ext = "JPG";
      else ext = "PNG";

      // circumvent security issues by disabling disk-based caching
      if (app.isApplet()) {
        javax.imageio.ImageIO.setUseCache(false);
      }

      ImageIO.write(img, ext, os);

      // restore caching to prevent side-effects
      if (app.isApplet()) {
        javax.imageio.ImageIO.setUseCache(true);
      }
    } catch (Exception e) {
      Application.debug(e.getMessage());
      try {
        // if this did not work save image as png
        ImageIO.write(img, "png", os);
      } catch (Exception ex) {
        Application.debug(ex.getMessage());
        return;
      }
    }
  }
Ejemplo n.º 3
0
  public static void main(String[] args) throws Exception {

    // String imgPath = "D:\\Users\\Zhangjunqiao\\3_Files";
    // try {
    // BufferedImage image = ImageIO.read(new FileInputStream(imgPath));
    // } catch (FileNotFoundException e) {
    // e.printStackTrace();
    // } catch (IOException e) {
    // e.printStackTrace();
    // }

    String content = "http://www.sinaimg.cn/dy/slidenews/8_img/2015_36/65486_439634_724233.jpg";

    BufferedImage image2 = QRCodeUtil.standEncodeQr(content);
    try {
      ImageIO.write(image2, "jpg", new File("D:\\Users\\Zhangjunqiao\\3_Files\\2.jpg"));
    } catch (IOException e) {
      e.printStackTrace();
    }

    String imgUrl = "http://www.qq1234.org/uploads/allimg/140714/3_140714160149_5.png"; // 小黄人
    try {
      BufferedImage image3 = QRCodeUtil.createImage(content, imgUrl);
      ImageIO.write(image3, "jpg", new File("D:\\Users\\Zhangjunqiao\\3_Files\\3.jpg"));
    } catch (Exception e) {
      e.printStackTrace();
    }
    File file = new File("D:\\Users\\Zhangjunqiao\\3_Files\\2.jpg");

    System.out.println("解析二维码的结果为:" + QRCodeUtil.decode(file));
  }
Ejemplo n.º 4
0
 public void actionPerformed(final ActionEvent e) {
   @SuppressWarnings("unchecked")
   final Pair<String, Component> p = (Pair<String, Component>) cboDisplayType.getSelectedItem();
   AbstractChart chart = null;
   Dimension chartSize = null;
   Stack<Rectangle2D> stack = null;
   String saveTitle = null;
   List<? extends FileFilter> filters = null;
   if (p.getSecond() == scpLineChart) {
     stack = stkLineChartZoom;
     chart = pnlLineChart;
     chartSize = new Dimension(1200, 400);
     saveTitle = "Save Landscape Line Chart";
     filters = FileSaver.fltGraphics;
   } else if (p.getSecond() == scpHistogram) {
     stack = stkHistogramZoom;
     chart = pnlHistogram;
     chartSize = new Dimension(1000, 1000);
     saveTitle = "Save Landscape Histogram";
     filters = FileSaver.fltGraphics;
   } else {
     saveTitle = "Save Landscape Raw Text";
     filters = FileSaver.fltText;
   }
   if ((e.getSource() == cmdUnzoom) && (stack != null) && (chart != null)) {
     final Rectangle2D viewport = stack.pop();
     chart.setViewport(viewport);
     checkEnabled(isEnabled());
   } else if ((e.getSource() == cmdResetView) && (stack != null) && (chart != null)) {
     chart.setViewport(stack.firstElement());
     stack.clear();
     checkEnabled(isEnabled());
   } else if (e.getSource() == cmdSave) {
     try {
       final Pair<File, FileFilter> ff =
           FileSaver.getSaveFile(getTopLevelAncestor(), saveTitle, filters);
       if (ff == null) {
         return;
       }
       if ((chart == null) || (chartSize == null)) {
         FileSaver.saveText(txaRaw.getText(), ff.getFirst());
       } else if (ff.getSecond() == FileSaver.epsFilter) {
         final Writer w = new FileWriter(ff.getFirst());
         w.write(chart.getEpsText(chartSize.width, chartSize.height));
         w.flush();
         w.close();
       } else if (ff.getSecond() == FileSaver.pngFilter) {
         ImageIO.write(chart.getImage(chartSize.width, chartSize.height), "png", ff.getFirst());
       } else if (ff.getSecond() == FileSaver.jpgFilter) {
         ImageIO.write(chart.getImage(chartSize.width, chartSize.height), "jpeg", ff.getFirst());
       }
     } catch (final IOException ex) {
       Utility.logException(ex);
       JOptionPane.showMessageDialog(
           getTopLevelAncestor(), ex.getMessage(), "I/O Error", JOptionPane.ERROR_MESSAGE);
     }
   } else {
     throw new IllegalArgumentException(e.getActionCommand());
   }
 }
Ejemplo n.º 5
0
  @Override
  protected AbstractView doService() throws MvcException {
    UserInfo userInfo = this.userInfoService.getCurrent();
    int uid = userInfo.getUser().getId();
    String rootPath = MvcContext.getInstance().getRootPath();
    String avatarPath = this.userInfoService.prepareUploadFolder();
    String finalPath = rootPath + avatarPath;
    logger.info("上传目录:" + finalPath);
    File file = this.saveFile("avatar", finalPath + "/o_" + uid);
    logger.info("保存头像到:" + file.getAbsolutePath());
    userInfo.getUser().setAvatar(avatarPath + "/" + file.getName());
    this.userService.save(userInfo.getUser());

    try { // 创建小、中、大头像
      String extension = StringUtil.substring2(file.getName(), ".").replace(".", "");
      if (StringUtil.isBlank(extension)) {
        extension = "png"; // 默认格式
      }
      BufferedImage image = ImageIO.read(file);
      BufferedImage largeAvatar = Scalr.resize(image, 128, 128); // 大头像
      ImageIO.write(largeAvatar, extension, new File(file.getAbsolutePath().replace("o_", "l_")));
      BufferedImage mediumAvatar = Scalr.resize(image, 48, 48); // 中头像
      ImageIO.write(mediumAvatar, extension, new File(file.getAbsolutePath().replace("o_", "m_")));
      BufferedImage smallAvatar = Scalr.resize(image, 16, 16); // 小头像
      ImageIO.write(smallAvatar, extension, new File(file.getAbsolutePath().replace("o_", "s_")));
    } catch (IOException e) {
      e.printStackTrace();
    }

    return new JsonResultView("file", avatarPath);
  }
Ejemplo n.º 6
0
  private <T> T scaleImageUsingAffineTransformation(final BufferedImage bufferedImage, T target) {
    BufferedImage destinationImage = generateDestinationImage();
    Graphics2D graphics2D = destinationImage.createGraphics();
    AffineTransform transformation =
        AffineTransform.getScaleInstance(
            ((double) getQualifiedWidth() / bufferedImage.getWidth()),
            ((double) getQualifiedHeight() / bufferedImage.getHeight()));
    graphics2D.drawRenderedImage(bufferedImage, transformation);
    graphics2D.addRenderingHints(retrieveRenderingHints());
    try {
      if (target instanceof File) {
        LOGGER.info(String.format(M_TARGET_TYPE_OF, "File"));
        ImageIO.write(destinationImage, imageType.toString(), (File) target);
      } else if (target instanceof ImageOutputStream) {
        LOGGER.info(String.format(M_TARGET_TYPE_OF, "ImageOutputStream"));
        ImageIO.write(destinationImage, imageType.toString(), (ImageOutputStream) target);
      } else if (target instanceof OutputStream) {
        LOGGER.info(String.format(M_TARGET_TYPE_OF, "OutputStream"));
        ImageIO.write(destinationImage, imageType.toString(), (OutputStream) target);
      } else {
        target = null;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    return target;
  }
    public GhostReport ghostCalculation(int maxImageSmallDimension, int numThreads)
        throws IOException {
      File ghostOutputfile;
      byte[] imageInByte;
      String ghostBase64; // convert to base64 the image file
      GhostReport ghostReport = new GhostReport();
      GhostExtractor ghostExtractor;
      ghostExtractor = new GhostExtractor(sourceFile, maxImageSmallDimension, numThreads);
      BufferedImage ghostMap;
      for (int ghostMapInd = 0; ghostMapInd < ghostExtractor.ghostMaps.size(); ghostMapInd++) {
        ghostOutputfile =
            new File(baseFolder, "GhostOutput" + String.format("%02d", ghostMapInd) + ".png");
        ghostMap = ghostExtractor.ghostMaps.get(ghostMapInd);
        ImageIO.write(ghostMap, "png", ghostOutputfile);
        ByteArrayOutputStream ghostbytes = new ByteArrayOutputStream();
        ImageIO.write(ghostMap, "png", ghostbytes);
        imageInByte = ghostbytes.toByteArray();

        ghostReport.maps.add(ghostOutputfile.getCanonicalPath());
        ghostReport.differences = ghostExtractor.allDifferences;
        ghostReport.minQuality = ghostExtractor.qualityMin;
        ghostReport.maxQuality = ghostExtractor.qualityMax;
        ghostReport.qualities = ghostExtractor.ghostQualities;
        ghostReport.minValues = ghostExtractor.ghostMin;
        ghostReport.maxValues = ghostExtractor.ghostMax;
      }
      ghostReport.completed = true;
      return ghostReport;
    }
Ejemplo n.º 8
0
  /**
   * Save onscreen image to file - suffix must be png, jpg, or gif.
   *
   * @param filename the name of the file with one of the required suffixes
   */
  public static void save(String filename) {
    File file = new File(filename);
    String suffix = filename.substring(filename.lastIndexOf('.') + 1);

    // png files
    if (suffix.toLowerCase().equals("png")) {
      try {
        ImageIO.write(onscreenImage, suffix, file);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // need to change from ARGB to RGB for jpeg
    // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727
    else if (suffix.toLowerCase().equals("jpg")) {
      WritableRaster raster = onscreenImage.getRaster();
      WritableRaster newRaster;
      newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});
      DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel();
      DirectColorModel newCM =
          new DirectColorModel(
              cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask());
      BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null);
      try {
        ImageIO.write(rgbBuffer, suffix, file);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      System.out.println("Invalid image file type: " + suffix);
    }
  }
    public GridsBothReport gridsCalculation() throws IOException {
      GridsBothReport gridsBothReport = new GridsBothReport();
      GridsExtractor gridsExtractor;
      gridsExtractor = new GridsExtractor(sourceFile);
      ImageIO.write(gridsExtractor.displaySurfaceG, "png", outputFileG);
      ByteArrayOutputStream gridsbytes = new ByteArrayOutputStream();
      ImageIO.write(gridsExtractor.displaySurfaceG, "png", gridsbytes);

      ImageIO.write(gridsExtractor.displaySurfaceGI, "png", outputFileGI);
      ByteArrayOutputStream gridsInvbytes = new ByteArrayOutputStream();
      ImageIO.write(gridsExtractor.displaySurfaceGI, "png", gridsInvbytes);

      gridsBothReport.mapG = outputFileG.getCanonicalPath();
      gridsBothReport.mapGI = outputFileGI.getCanonicalPath();
      gridsBothReport.maxValueG = gridsExtractor.gridsmaxG;
      gridsBothReport.minValueG = gridsExtractor.gridsminG;
      gridsBothReport.maxValueG = gridsExtractor.gridsmaxGI;
      gridsBothReport.minValueG = gridsExtractor.gridsminGI;
      gridsBothReport.completed = true;

      gridsBothReport.gridsNormalReport.map = outputFileG.getCanonicalPath();
      gridsBothReport.gridsNormalReport.maxValue = gridsExtractor.gridsmaxG;
      gridsBothReport.gridsNormalReport.minValue = gridsExtractor.gridsminG;
      gridsBothReport.gridsNormalReport.completed = true;

      gridsBothReport.gridsInversedReport.map = outputFileGI.getCanonicalPath();
      gridsBothReport.gridsInversedReport.maxValue = gridsExtractor.gridsmaxGI;
      gridsBothReport.gridsInversedReport.minValue = gridsExtractor.gridsminGI;
      gridsBothReport.gridsInversedReport.completed = true;
      return gridsBothReport;
    }
Ejemplo n.º 10
0
 /**
  * Generates random, smooth and perlin noise images
  *
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
   float[][] noise =
       PerlinNoiseGenerator.whiteNoise(800, 800, ThreadLocalRandom.current().nextLong());
   ImageIO.write(heightMapToImage(noise), "jpg", new File("noise.jpg"));
   float[][] smooth = PerlinNoiseGenerator.smoothNoise(noise, 0);
   ImageIO.write(heightMapToImage(smooth), "jpg", new File("smooth.jpg"));
   float[][] perlin = PerlinNoiseGenerator.perlinNoise(noise, 15, 0.962F);
   ImageIO.write(heightMapToImage(perlin), "jpg", new File("perlin.jpg"));
 }
  @Override
  public CCPCBillInfo queryCCPCBillInfo(String mrchNo, String rmtAccNo, String payNo) {
    CCPCBillInfo billInfo = null;
    PayCCPC payCCPC = payCCPCService.findPayCCPCByPayNoAndMrchNo(payNo, mrchNo);
    if (payCCPC != null) {
      if (StringUtils.isNotBlank(rmtAccNo)) {
        if (payCCPC.getRmtAccNo().equals(rmtAccNo)) {
          throw new AppRTException(
              AppExCode.ILLEGAL_PARAMS,
              "非法数据,transRefNo["
                  + payNo
                  + "]对应rmtAccNo["
                  + rmtAccNo
                  + "],但查出的是rmtAccNo["
                  + payCCPC.getRmtAccNo()
                  + "]");
        }
      }
      billInfo = XPOSPClientUtils.payCCPCToCCPCBillInfo(payCCPC);

      String elecsignsPath =
          XpospSysProperty.getESignaturePath()
              + payCCPC.getMrchNo()
              + File.separatorChar
              + payCCPC.getStoreNo()
              + File.separatorChar;
      String rmtElecSignDataFileName =
          payNo + "-rmt" + "." + XPOSPClientUtils.ESIGNATURE_PICTURE_SUFFIX;
      String bnyElecSignDataFileName =
          payNo + "-bny" + "." + XPOSPClientUtils.ESIGNATURE_PICTURE_SUFFIX;
      File remitElecSignDataFile = new File(elecsignsPath + rmtElecSignDataFileName);
      File bnyElecSignDataFile = new File(elecsignsPath + bnyElecSignDataFileName);
      if (remitElecSignDataFile.exists()) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedImage image;
        try {
          image = ImageIO.read(remitElecSignDataFile);
          ImageIO.write(image, XPOSPClientUtils.BILLINFO_PICTURE_SUFFIX, out);
          billInfo.setRmtElecsignData(CodecUtils.hexString(out.toByteArray()));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (bnyElecSignDataFile.exists()) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedImage image;
        try {
          image = ImageIO.read(bnyElecSignDataFile);
          ImageIO.write(image, XPOSPClientUtils.BILLINFO_PICTURE_SUFFIX, out);
          billInfo.setBnyElecsignData(CodecUtils.hexString(out.toByteArray()));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return billInfo;
  }
Ejemplo n.º 12
0
  public void getImage() throws IOException {

    files.clear();
    allBlackObjects.clear();
    fieldObjectPixels.clear();
    points = null;
    next = null;

    File gameImage1 = new File("d://liga/szene1.png");
    File output = new File("d://liga/out.png");

    /* Color Image*/
    BufferedImage bi = ImageIO.read(gameImage1);
    BufferedImage colorImage =
        new BufferedImage(bi.getWidth(null), bi.getHeight(null), BufferedImage.TYPE_BYTE_BINARY);
    // colorImage = new Contrast(image).contrast(0.3);

    Graphics2D gColor = (Graphics2D) colorImage.getGraphics();
    gColor.drawImage(bi, 0, 0, null);
    // Save Color Img as output.png
    String outputPath = "d://liga/output.png";
    File outputFile = new File(outputPath);
    ImageIO.write(colorImage, "png", outputFile);
    System.out.println("test");

    /* Get image resolution */
    width = bi.getWidth();
    height = bi.getHeight();

    /* GEHE JEDEN PIXEL DURCH */
    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        // Test every Pixel if Colored or not
        /* WENN AKTUELLE PIXELFARBE -1 < 0 IST */
        /** SUCHE GRÜN * */
        Color tempCol = new Color(colorImage.getRGB(x, y));
        if (tempCol.getGreen() > 100) {
          // System.out.println(tempCol.getGreen());
          if ((colorImage.getRGB(x, y)) < -1) {
            Point tempPoint = new Point(x, y);
            tempPoint.setColor(colorImage.getRGB(x, y));
            fieldObjectPixels.add(tempPoint);
          }
        }
      }
    }
    if (fieldObjectPixels.size() > 0) {
      // Go on
      createFieldObject();
    } else {
      System.out.println("No colored FieldObjects found.");
    }

    gColor.dispose();
    ImageIO.write(colorImage, "png", output);
  }
Ejemplo n.º 13
0
  public Element exec(Element params, ServiceContext context) throws Exception {

    Path harvestingLogoDirectory = Resources.locateHarvesterLogosDir(context);
    Path nodeLogoDirectory = Resources.locateLogosDir(context);

    String file = Util.getParam(params, Params.FNAME);
    String asFavicon = Util.getParam(params, Params.FAVICON, "0");

    if (file.contains("..")) {
      throw new BadParameterEx("Invalid character found in resource name.", file);
    }

    if ("".equals(file)) {
      throw new Exception("Logo name is not defined.");
    }

    SettingManager settingMan = context.getBean(SettingManager.class);
    String nodeUuid = settingMan.getSiteId();

    try {
      Path logoFilePath = harvestingLogoDirectory.resolve(file);
      if (!Files.exists(logoFilePath)) {
        logoFilePath = context.getAppPath().resolve("images/harvesting/" + file);
      }
      try (InputStream inputStream = Files.newInputStream(logoFilePath)) {
        BufferedImage source = ImageIO.read(inputStream);

        if ("1".equals(asFavicon)) {
          createFavicon(source, nodeLogoDirectory.resolve("favicon.png"));
        } else {
          Path logo = nodeLogoDirectory.resolve(nodeUuid + ".png");
          Path defaultLogo = nodeLogoDirectory.resolve("logo.png");

          if (!file.endsWith(".png")) {
            try (OutputStream logoOut = Files.newOutputStream(logo);
                OutputStream defLogoOut = Files.newOutputStream(defaultLogo); ) {
              ImageIO.write(source, "png", logoOut);
              ImageIO.write(source, "png", defLogoOut);
            }
          } else {
            Files.deleteIfExists(logo);
            IO.copyDirectoryOrFile(logoFilePath, logo, false);
            Files.deleteIfExists(defaultLogo);
            IO.copyDirectoryOrFile(logoFilePath, defaultLogo, false);
          }
        }
      }
    } catch (Exception e) {
      throw new Exception(
          "Unable to move uploaded thumbnail to destination directory. Error: " + e.getMessage());
    }

    Element response = new Element("response");
    response.addContent(new Element("status").setText("Logo set."));
    return response;
  }
Ejemplo n.º 14
0
  private void lisaaUusiTiedosto(File uusiTiedosto) {
    BufferedImage uusiKuva = null;

    // System.out.println(kuvaLista.getModel().getSize() - 1);
    // Jos valittu tiedosto oli oikeaa muotoa luodaan siintä .bmp ja .jpg tiedostot .bmp
    // ratkaisemista varten
    // .jpg tiedoston näyttämistä varten ja muutetaan kuvien koko 450x450 jotta kuvat asettuu
    // ohjelmaan hyvin.
    // Muutetaan myös kuvan nimi kuva....
    File uusiKuvaTiedostoJpg =
        new File(
            tiedostojenSijainti
                + "/Kuvat/kuva"
                + ((kuvaLista.getModel().getSize() - 1) + 1)
                + ".jpg");
    File uusiKuvaTiedostoBmp =
        new File(
            tiedostojenSijainti
                + "/Kuvat/kuva"
                + ((kuvaLista.getModel().getSize() - 1) + 1)
                + ".bmp");
    try {
      uusiKuva = ImageIO.read(uusiTiedosto); // Ladataan käsiteltävä kuva uusiKuva muuttujaan
      if (uusiKuva.getHeight() > 450 || uusiKuva.getWidth() > 450) {
        BufferedImage uusiKokoKuvaan = new BufferedImage(450, 450, 1);
        Graphics2D g = uusiKokoKuvaan.createGraphics();
        g.drawImage(uusiKuva, 0, 0, 450, 450, null);
        g.dispose();
        uusiKuva = uusiKokoKuvaan;
      }
      ImageIO.write(uusiKuva, "jpg", uusiKuvaTiedostoJpg);
      ImageIO.write(uusiKuva, "bmp", uusiKuvaTiedostoBmp);

    } catch (IOException e) {
      System.out.println(e); // Tulostetaan virhe jos sellainen tulee
    }
    try {
      // Päivitetään valinta listan tiedot uudella kuvalla
      FileWriter asetuksetTiedosto = new FileWriter(tiedostojenSijainti + "/asetukset.txt");
      try (BufferedWriter asennusTiedostonPaivitys = new BufferedWriter(asetuksetTiedosto)) {
        for (int i = 0; i <= (kuvaLista.getModel().getSize() - 1); i++) {
          asennusTiedostonPaivitys.write(kuvaLista.getModel().getElementAt(i).toString() + "\n");
        }
        asennusTiedostonPaivitys.write("Kuva" + ((kuvaLista.getModel().getSize() - 1) + 2));
      }
      valintaListanTiedot();
    } catch (IOException ex) {
      Logger.getLogger(EtsiReittiUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    kuvanAlkuPiste.setText("" + 0);
    kuvanLoppuPiste.setText("" + 0);
    reitinPituus.setText("" + 0);
    kulunutAika.setText("" + 0);
  }
  private void _generateImagesPB(
      FileVersion fileVersion,
      PDPage pdPage,
      int dpi,
      int height,
      int width,
      boolean thumbnail,
      int index)
      throws Exception {

    // Generate images

    RenderedImage renderedImage =
        pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, PropsValues.DL_FILE_ENTRY_THUMBNAIL_DPI);

    if (height != 0) {
      renderedImage = ImageProcessorUtil.scale(renderedImage, width, height);
    } else {
      renderedImage = ImageProcessorUtil.scale(renderedImage, width);
    }

    // Store images

    String tempFileId =
        DLUtil.getTempFileId(fileVersion.getFileEntryId(), fileVersion.getVersion());

    File thumbnailTempFile = null;

    try {
      if (thumbnail) {
        thumbnailTempFile = getThumbnailTempFile(tempFileId);

        thumbnailTempFile.createNewFile();

        ImageIO.write(renderedImage, THUMBNAIL_TYPE, new FileOutputStream(thumbnailTempFile));

        addFileToStore(
            fileVersion.getCompanyId(), THUMBNAIL_PATH,
            getThumbnailFilePath(fileVersion), thumbnailTempFile);
      } else {
        thumbnailTempFile = getPreviewTempFile(tempFileId, index);

        thumbnailTempFile.createNewFile();

        ImageIO.write(renderedImage, PREVIEW_TYPE, new FileOutputStream(thumbnailTempFile));

        addFileToStore(
            fileVersion.getCompanyId(), PREVIEW_PATH,
            getPreviewFilePath(fileVersion, index), thumbnailTempFile);
      }
    } finally {
      FileUtil.delete(thumbnailTempFile);
    }
  }
Ejemplo n.º 16
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);
   }
 }
Ejemplo n.º 17
0
    public MedianNoiseReport medianNoiseCalculation() throws IOException {
      MedianNoiseReport medianNoiseReport = new MedianNoiseReport();
      MedianNoiseExtractor medianNoiseExtractor;
      medianNoiseExtractor = new MedianNoiseExtractor(sourceFile);
      ImageIO.write(medianNoiseExtractor.displaySurface, "png", outputFile);
      ByteArrayOutputStream medianNoisebytes = new ByteArrayOutputStream();
      ImageIO.write(medianNoiseExtractor.displaySurface, "png", medianNoisebytes);

      medianNoiseReport.map = outputFile.getCanonicalPath();
      medianNoiseReport.completed = true;
      return medianNoiseReport;
    }
Ejemplo n.º 18
0
  private static void assertEquals(
      File expectedFile, RenderedImage actualImage, int threshold, boolean actualReferenceFile) {
    // do we have the reference image at all?
    if (!expectedFile.exists()) {

      // see what the user thinks of the image
      boolean useAsReference =
          actualReferenceFile
              && INTERACTIVE
              && ReferenceImageDialog.show(realignImage(actualImage));
      if (useAsReference) {
        try {
          String format = getFormat(expectedFile);
          new ImageWorker(actualImage).writePNG(expectedFile, "FILTERED", 0.9f, false, false);
        } catch (IOException e) {
          throw (Error) new AssertionError("Failed to write the image to disk").initCause(e);
        }
      } else {
        throw new AssertionError("Reference image is missing: " + expectedFile);
      }
    } else {
      File actualFile = new File("target/actual.png");
      try {
        ImageIO.write(actualImage, "PNG", actualFile);

        Difference difference = PerceptualDiff.compareImages(expectedFile, actualFile, threshold);
        if (difference.imagesDifferent) {
          // check with the user
          boolean overwrite = false;
          if (INTERACTIVE) {
            RenderedImage expectedImage = ImageIO.read(expectedFile);
            overwrite =
                CompareImageDialog.show(
                    realignImage(expectedImage), realignImage(actualImage), actualReferenceFile);
          }

          if (overwrite) {
            ImageIO.write(actualImage, "PNG", expectedFile);
          } else {
            throw new AssertionError(
                "Images are visibly different, PerceptualDiff output is: " + difference.output);
          }
        } else {
          LOGGER.info("Images are equals, PerceptualDiff output is: " + difference.output);
        }
      } catch (IOException e) {
        throw (Error) new AssertionError("Failed to write the image to disk").initCause(e);
      } finally {
        actualFile.delete();
      }
    }
  }
Ejemplo n.º 19
0
 public dqReport dqCalculation() throws IOException {
   dqReport dqReport = new dqReport();
   DQExtractor dqDetector;
   dqDetector = new DQExtractor(sourceFile);
   ImageIO.write(dqDetector.displaySurface, "png", outputFile);
   ByteArrayOutputStream dqbytes = new ByteArrayOutputStream();
   ImageIO.write(dqDetector.displaySurface, "png", dqbytes);
   dqReport.map = outputFile.getCanonicalPath();
   dqReport.maxValue = dqDetector.maxProbValue;
   dqReport.minvalue = dqDetector.minProbValue;
   dqReport.completed = true;
   return dqReport;
 }
Ejemplo n.º 20
0
  public static ScalingReport scale(byte[] fileData, int width, int height)
      throws ApplicationException {
    ByteArrayInputStream in = new ByteArrayInputStream(fileData);
    ScalingReport imagedata = new ScalingReport();
    try {

      BufferedImage img = ImageIO.read(in);

      if (img.getHeight() > img.getWidth()) {
        if (img.getHeight() > height) {
          width = (height * img.getWidth()) / img.getHeight();
          Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
          BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
          imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null);

          ByteArrayOutputStream buffer = new ByteArrayOutputStream();
          ImageIO.write(imageBuff, "jpg", buffer);
          imagedata.scaledByte = buffer.toByteArray();
          imagedata.width = width;
          imagedata.height = height;
        } else {
          imagedata.scaledByte = fileData;
          imagedata.width = img.getWidth();
          imagedata.height = img.getHeight();
        }
      } else {
        if (img.getWidth() > width) {
          height = (width * img.getHeight()) / img.getWidth();

          Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
          BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
          imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null);

          ByteArrayOutputStream buffer = new ByteArrayOutputStream();

          ImageIO.write(imageBuff, "jpg", buffer);
          imagedata.scaledByte = buffer.toByteArray();
          imagedata.width = width;
          imagedata.height = height;
        } else {
          imagedata.scaledByte = fileData;
          imagedata.width = img.getWidth();
          imagedata.height = img.getHeight();
        }
      }
      return imagedata;
    } catch (IOException e) {
      throw new ApplicationException("IOException in scale", null);
    }
  }
Ejemplo n.º 21
0
    public DWNoiseReport noiseDWCalculation() throws IOException {
      DWNoiseReport dwNoiseReport = new DWNoiseReport();
      DWNoiseVarExtractor noiseExtractor;
      noiseExtractor = new DWNoiseVarExtractor(sourceFile);
      ImageIO.write(noiseExtractor.displaySurface, "png", outputFile);
      ByteArrayOutputStream noisebytes = new ByteArrayOutputStream();
      ImageIO.write(noiseExtractor.displaySurface, "png", noisebytes);

      dwNoiseReport.map = outputFile.getCanonicalPath();
      dwNoiseReport.maxvalue = noiseExtractor.maxNoiseValue;
      dwNoiseReport.minValue = noiseExtractor.minNoiseValue;
      dwNoiseReport.completed = true;
      return dwNoiseReport;
    }
Ejemplo n.º 22
0
    public ELAReport elaCalculation() throws IOException {
      ELAReport elaReport = new ELAReport();
      ELAExtractor elaExtractor;
      elaExtractor = new ELAExtractor(sourceFile);
      ImageIO.write(elaExtractor.displaySurface, "png", outputFile);
      ByteArrayOutputStream elabytes = new ByteArrayOutputStream();
      ImageIO.write(elaExtractor.displaySurface, "png", elabytes);

      elaReport.map = outputFile.getCanonicalPath();
      elaReport.maxValue = elaExtractor.elaMax;
      elaReport.minvalue = elaExtractor.elaMin;
      elaReport.completed = true;
      return elaReport;
    }
Ejemplo n.º 23
0
    public BlockingReport blkCalculation() throws IOException {
      BlockingReport blockingReport = new BlockingReport();
      BlockingExtractor blockingExtractor;
      blockingExtractor = new BlockingExtractor(sourceFile);
      ImageIO.write(blockingExtractor.displaySurface, "png", outputFile);
      ByteArrayOutputStream blockbytes = new ByteArrayOutputStream();
      ImageIO.write(blockingExtractor.displaySurface, "png", blockbytes);

      blockingReport.map = outputFile.getCanonicalPath();
      blockingReport.maxValue = blockingExtractor.blkmax;
      blockingReport.minValue = blockingExtractor.blkmin;
      blockingReport.completed = true;
      return blockingReport;
    }
  /**
   * Takes a screenshot and saves the image to disk. This method will attempt to encode the image
   * according to the file extension of the given output file. If this is not possible (because the
   * encoding type is not supported), then the default encoding type will be used. If the default
   * encoding type is used, an appropriate extension will be added to the filename.
   *
   * @param captureRect Rect to capture in screen coordinates.
   * @param scaleFactor Degree to which the image should be scaled, in percent. A <code>scaleFactor
   *     </code> of <code>100</code> produces an unscaled image. This value must be greater than
   *     <code>0</code> and less than or equal to <code>200</code>.
   * @param outputFile Path and filename for the created image.
   */
  public void takeScreenshot(Rectangle captureRect, double scaleFactor, File outputFile) {
    // Create screenshot
    java.awt.Robot robot;
    File out = outputFile;

    try {
      robot = new java.awt.Robot();
      BufferedImage image = robot.createScreenCapture(captureRect);

      int scaledWidth = (int) Math.floor(image.getWidth() * scaleFactor);
      int scaledHeight = (int) Math.floor(image.getHeight() * scaleFactor);
      BufferedImage imageOut =
          new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
      // Scale it to the new size on-the-fly
      Graphics2D graphics2D = imageOut.createGraphics();
      graphics2D.setRenderingHint(
          RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
      graphics2D.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);

      // Save captured image using given format, if supported.
      String extension = getExtension(out.getName());
      if (extension.length() == 0
          || !ImageIO.getImageWritersBySuffix(extension).hasNext()
          || !ImageIO.write(imageOut, extension, out)) {

        // Otherwise, save using default format
        out = new File(outputFile.getPath() + EXTENSION_SEPARATOR + DEFAULT_IMAGE_FORMAT);
        if (!ImageIO.write(imageOut, DEFAULT_IMAGE_FORMAT, out)) {

          // This should never happen, so log as error if it does.
          // In this situation, the screenshot will not be saved, but
          // the test step will still be marked as successful.
          log.error(
              "Screenshot could not be saved. "
                  + //$NON-NLS-1$
                  "Default image format ("
                  + DEFAULT_IMAGE_FORMAT //$NON-NLS-1$
                  + ") is not supported."); //$NON-NLS-1$
        }
      }

    } catch (AWTException e) {
      throw new RobotException(e);
    } catch (IOException e) {
      throw new StepExecutionException(
          "Screenshot could not be saved", //$NON-NLS-1$
          EventFactory.createActionError(TestErrorEvent.FILE_IO_ERROR));
    }
  }
Ejemplo n.º 25
0
  public void test_code() throws Exception {
    String data = "知遇\[email protected]\nqq: 273090727";
    BufferedImage img = qrcoder.encode(data);
    ImageIO.write(img, "png", new File("e:\\default.png"));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(img, "png", out);
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    out.close();
    System.out.println(in.available());
    String result = qrcoder.decode(in);
    in.close();

    Assert.assertEquals(data, result);
    System.out.println(result);
  }
Ejemplo n.º 26
0
  public static void main(String[] args) {
    try {
      // create the plotting domain
      final int WIDTH = 1024;
      final int HEIGHT = 512;
      BoundingBox bbox = new BoundingBoxImpl(-180, -90, 180, 90, DefaultGeographicCRS.WGS84);
      PlottingDomainParams params =
          new PlottingDomainParams(WIDTH, HEIGHT, bbox, null, null, null, null, null);

      // load the datasets from a config file
      DatasetFactory.setDefaultDatasetFactoryClass(CdmGridDatasetFactory.class);
      NcwmsConfig config =
          NcwmsConfig.readFromFile(new File("C:\\Users\\Charles\\.ncWMS-edal\\config.xml"));

      // create the feature catalogue
      FeatureCatalogue catalogue = new NcwmsCatalogue(config);

      try {
        Thread.sleep(3000);
      } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
      }

      // process each XML file
      final File folder = new File("N:\\Documents\\SLDInput");
      for (final File fileEntry : folder.listFiles()) {
        String fileName = fileEntry.getName();
        if (fileName.endsWith("xml")) {
          System.out.println("Processing " + fileName);
          // create the image from the XML file
          MapImage mapImage = StyleSLDParser.createImage(fileEntry);
          BufferedImage image = mapImage.drawImage(params, catalogue);
          // write the image to a PNG file
          File outputfile = new File("N:\\Documents\\SLDOutput\\" + fileName.replace("xml", "png"));
          ImageIO.write(image, "png", outputfile);
          // create the legend
          BufferedImage legend = mapImage.getLegend(250);
          outputfile =
              new File("N:\\Documents\\SLDOutput\\" + fileName.replace(".xml", "_lgd.png"));
          ImageIO.write(legend, "png", outputfile);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    NcwmsConfig.shutdown();
  }
Ejemplo n.º 27
0
  /** @param args */
  public static void main(String[] args) {
    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(null);
    File file = chooser.getSelectedFile();
    String indir = file.getAbsolutePath();
    BufferedImage out = null;
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
      out = new BufferedImage(256, 1, BufferedImage.TYPE_INT_RGB);
      String sCurrentLine;
      int pos = 0;
      while ((sCurrentLine = br.readLine()) != null) {
        String[] values = sCurrentLine.split(" ");
        Color ocol =
            new Color(
                Integer.valueOf(values[0]), Integer.valueOf(values[1]), Integer.valueOf(values[2]));
        out.setRGB(pos, 0, ocol.getRGB());
        pos++;
      }
      File outputimage = new File("C:\\ydkj\\palette", "GENPALETTE.bmp");
      ImageIO.write(out, "bmp", outputimage);

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 28
0
 /** Write the image */
 public void writeImage() {
   try {
     ImageIO.write(bufferedImage, "png", (new File(filename.replace(".png", "_diff_map.png"))));
   } catch (IOException e) {
     System.out.println("Couldn't write file!");
   }
 }
Ejemplo n.º 29
0
  public static void main(String[] args) {
    try {
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

      File input = new File("traffic_signal.jpg");
      BufferedImage image = ImageIO.read(input);

      byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
      Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
      mat.put(0, 0, data);

      Mat mat1 = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1);
      Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY);

      byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int) (mat1.elemSize())];
      mat1.get(0, 0, data1);
      BufferedImage image1 =
          new BufferedImage(mat1.cols(), mat1.rows(), BufferedImage.TYPE_BYTE_GRAY);
      image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1);

      File ouptut = new File("output\\grayscale_" + new Date().getTime() + ".jpg");
      ImageIO.write(image1, "jpg", ouptut);
    } catch (Exception e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
Ejemplo n.º 30
0
  /**
   * 将照片logo添加到二维码中间
   *
   * @param image 生成的二维码照片对象
   * @param imagePath 照片保存路径
   * @param logoPath logo照片路径
   * @param formate 照片格式
   */
  public static void overlapImage(
      BufferedImage image,
      String formate,
      String imagePath,
      String logoPath,
      MatrixToLogoImageConfig logoConfig) {
    try {
      BufferedImage logo = ImageIO.read(new File(logoPath));
      Graphics2D g = image.createGraphics();
      // 考虑到logo照片贴到二维码中,建议大小不要超过二维码的1/5;
      int width = image.getWidth() / logoConfig.getLogoPart();
      int height = image.getHeight() / logoConfig.getLogoPart();
      // logo起始位置,此目的是为logo居中显示
      int x = (image.getWidth() - width) / 2;
      int y = (image.getHeight() - height) / 2;
      // 绘制图
      g.drawImage(logo, x, y, width, height, null);

      // 给logo画边框
      // 构造一个具有指定线条宽度以及 cap 和 join 风格的默认值的实心 BasicStroke
      g.setStroke(new BasicStroke(logoConfig.getBorder()));
      g.setColor(logoConfig.getBorderColor());
      g.drawRect(x, y, width, height);

      g.dispose();
      // 写入logo照片到二维码
      ImageIO.write(image, formate, new File(imagePath));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }