Beispiel #1
0
  @Override
  public Raster readRaster(int frameIndex, ImageReadParam param) throws IOException {
    readMetadata();
    checkIndex(frameIndex);

    if (decompressor != null) {
      decompressor.setInput(iisOfFrame(frameIndex));

      if (LOG.isDebugEnabled()) LOG.debug("Start decompressing frame #" + (frameIndex + 1));
      Raster wr =
          pmi.decompress() == pmi && decompressor.canReadRaster()
              ? decompressor.readRaster(0, decompressParam(param))
              : decompressor.read(0, decompressParam(param)).getRaster();
      if (LOG.isDebugEnabled()) LOG.debug("Finished decompressing frame #" + (frameIndex + 1));
      return wr;
    }
    iis.seek(pixeldata.offset + frameIndex * frameLength);
    WritableRaster wr = Raster.createWritableRaster(createSampleModel(dataType, banded), null);
    DataBuffer buf = wr.getDataBuffer();
    if (buf instanceof DataBufferByte) {
      byte[][] data = ((DataBufferByte) buf).getBankData();
      for (byte[] bs : data) iis.readFully(bs);
      if (pixeldata.bigEndian && pixeldataVR.vr == VR.OW) ByteUtils.swapShorts(data);
    } else {
      short[] data = ((DataBufferUShort) buf).getData();
      iis.readFully(data, 0, data.length);
    }
    return wr;
  }
Beispiel #2
0
    @Override
    protected void ensureContentAvailable() {
      if (!isContentAvailable()) {
        try {
          contentURL = createWadoURL(getMimeType(), -1);
        } catch (Exception e) {
          log.error("Unable to get image document WADO URL!", e);
        }
        try {
          Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("dicom");
          if (readers != null && readers.hasNext()) {
            List<org.dcm4chee.archive.entity.File> files =
                ((TCQueryLocal) JNDIUtils.lookup(TCQueryLocal.JNDI_NAME))
                    .findInstanceByUID(getSOPInstanceUID())
                    .getFiles();
            String fsId = files.get(0).getFileSystem().getDirectoryPath();
            String fileId = files.get(0).getFilePath();

            ImageReader reader = readers.next();
            reader.setInput(
                ImageIO.createImageInputStream(
                    fsId.startsWith("tar:")
                        ? TarRetrieveDelegate.getInstance().retrieveFileFromTar(fsId, fileId)
                        : FileUtils.resolve(new File(fsId, fileId))),
                true);
            contentImage = reader.read(0);
            thumbnailImage = toThumbnailImage(contentImage);
          }
        } catch (Exception e) {
          log.error("Unable to convert encapsulated image to image!", e);
        }
      }
    }
Beispiel #3
0
  public static BufferedImage getImage(File imageFile) {

    BufferedImage al = null;

    try {

      String imageFileName = imageFile.getName();

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

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

      ImageReader reader = readers.next();
      if (reader == null) {

        JOptionPane.showConfirmDialog(
            null, "Need to install JAI Image I/O package./nhttps://jai-imageio.dev.java.net");

        return null;
      }
      ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
      reader.setInput(iis);
      al = reader.read(0);
      reader.dispose();

    } catch (IOException ioe) {
      System.err.println(ioe.getMessage());
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
    return al;
  }
Beispiel #4
0
  /**
   * Gets pixel data of an <code>IIOImage</code> object.
   *
   * @param oimage an <code>IIOImage</code> object
   * @return a byte buffer of pixel data
   * @throws Exception
   */
  public static ByteBuffer getImageByteBuffer(BufferedImage oimage) throws IOException {
    // Get tif writer and set output to file
    ImageWriter writer = new TIFFImageWriterSpi().createWriterInstance();

    // Set up the writeParam
    // We are using the old JAI ImageIO plugin, because for some reason, OCR don't work with
    // TwelveMonkeys' plugin
    ImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    // 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(oimage, null, null), tiffWriteParam);
    writer.dispose();

    // Read the writed image
    ios.seek(0);
    ImageReader reader = new TIFFImageReaderSpi().createReaderInstance();
    ImageReadParam param = reader.getDefaultReadParam();
    reader.setInput(ios, true, true);
    BufferedImage bi;
    try {
      bi = reader.read(0, param);
    } finally {
      reader.dispose();
      ios.close();
    }

    return convertImageData(bi);
  }
Beispiel #5
0
 private BufferedImage getImage(File file) {
   ImageInputStream iis = null;
   BufferedImage image = null;
   try {
     iis = ImageIO.createImageInputStream(file);
     Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
     if (!it.hasNext()) throw new UnsupportedOperationException("No image reader fround.");
     ImageReader reader = it.next();
     reader.setInput(iis);
     int scaleFactor;
     if (reader.getWidth(0) >= reader.getHeight(0))
       scaleFactor = Math.round(((float) reader.getWidth(0)) / MAX_SIZE);
     else scaleFactor = Math.round(((float) reader.getHeight(0)) / MAX_SIZE);
     ImageReadParam param = reader.getDefaultReadParam();
     param.setSourceSubsampling(scaleFactor, scaleFactor, 0, 0);
     image = reader.read(0, param);
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (iis != null)
       try {
         iis.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
   }
   return image;
 }
Beispiel #6
0
  @Override
  public BufferedImage read(int frameIndex, ImageReadParam param) throws IOException {
    readMetadata();
    checkIndex(frameIndex);

    WritableRaster raster;
    if (decompressor != null) {
      decompressor.setInput(iisOfFrame(frameIndex));
      if (LOG.isDebugEnabled()) LOG.debug("Start decompressing frame #" + (frameIndex + 1));
      BufferedImage bi = decompressor.read(0, decompressParam(param));
      if (LOG.isDebugEnabled()) LOG.debug("Finished decompressing frame #" + (frameIndex + 1));
      if (samples > 1) return bi;

      raster = bi.getRaster();
    } else raster = (WritableRaster) readRaster(frameIndex, param);

    ColorModel cm;
    if (pmi.isMonochrome()) {
      int[] overlayGroupOffsets = getActiveOverlayGroupOffsets(param);
      byte[][] overlayData = new byte[overlayGroupOffsets.length][];
      for (int i = 0; i < overlayGroupOffsets.length; i++) {
        overlayData[i] = extractOverlay(overlayGroupOffsets[i], raster);
      }
      cm = createColorModel(8, DataBuffer.TYPE_BYTE);
      SampleModel sm = createSampleModel(DataBuffer.TYPE_BYTE, false);
      raster = applyLUTs(raster, frameIndex, param, sm, 8);
      for (int i = 0; i < overlayGroupOffsets.length; i++) {
        applyOverlay(overlayGroupOffsets[i], raster, frameIndex, param, 8, overlayData[i]);
      }
    } else {
      cm = createColorModel(bitsStored, dataType);
    }
    return new BufferedImage(cm, raster, false, null);
  }
  @Override
  public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage)
      throws IOException, HttpMessageNotReadableException {

    ImageInputStream imageInputStream = null;
    ImageReader imageReader = null;
    try {
      imageInputStream = createImageInputStream(inputMessage.getBody());
      MediaType contentType = inputMessage.getHeaders().getContentType();
      Iterator<ImageReader> imageReaders =
          ImageIO.getImageReadersByMIMEType(contentType.toString());
      if (imageReaders.hasNext()) {
        imageReader = imageReaders.next();
        ImageReadParam irp = imageReader.getDefaultReadParam();
        process(irp);
        imageReader.setInput(imageInputStream, true);
        return imageReader.read(0, irp);
      } else {
        throw new HttpMessageNotReadableException(
            "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]");
      }
    } finally {
      if (imageReader != null) {
        imageReader.dispose();
      }
      if (imageInputStream != null) {
        try {
          imageInputStream.close();
        } catch (IOException ex) {
          // ignore
        }
      }
    }
  }
Beispiel #8
0
  /**
   * 图片文件转换为tif格式
   *
   * @param imageFile 文件路径
   * @param imageFormat 文件扩展名
   * @return
   */
  public static File createImage(File imageFile, String imageFormat) {
    File tempFile = null;
    try {
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
      ImageReader reader = readers.next();

      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.CHINESE);
      tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

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

      BufferedImage bi = reader.read(0);
      IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0));
      tempFile = tempImageFile(imageFile);
      ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
      writer.setOutput(ios);
      writer.write(streamMetadata, image, tiffWriteParam);
      ios.close();

      writer.dispose();
      reader.dispose();

    } catch (IOException e) {
      e.printStackTrace();
    }
    return tempFile;
  }
Beispiel #9
0
  public static BufferedImage decodeWebP(InputStream is) throws IOException {

    ImageReader imageReader = getReader();
    ImageInputStream iis = ImageIO.createImageInputStream(is);
    imageReader.setInput(iis, false);

    return imageReader.read(0);
  }
 /**
  * Decode JBIG2 data using Java ImageIO library.
  *
  * <p>{@inheritDoc}
  */
 public void decode(
     InputStream compressedData, OutputStream result, COSDictionary options, int filterIndex)
     throws IOException {
   /**
    * A working JBIG2 ImageIO plugin is needed to decode JBIG2 encoded streams. The following is
    * known to be working. It can't be bundled with PDFBox because of an incompatible license.
    * http://code.google.com/p/jbig2-imageio/
    */
   Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JBIG2");
   if (!readers.hasNext()) {
     LOG.error("Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.");
     return;
   }
   ImageReader reader = readers.next();
   COSDictionary decodeP = (COSDictionary) options.getDictionaryObject(COSName.DECODE_PARMS);
   COSInteger bits = (COSInteger) options.getDictionaryObject(COSName.BITS_PER_COMPONENT);
   COSStream st = null;
   if (decodeP != null) {
     st = (COSStream) decodeP.getDictionaryObject(COSName.JBIG2_GLOBALS);
   }
   if (st != null) {
     reader.setInput(
         ImageIO.createImageInputStream(
             new SequenceInputStream(st.getFilteredStream(), compressedData)));
   } else {
     reader.setInput(ImageIO.createImageInputStream(compressedData));
   }
   BufferedImage bi = reader.read(0);
   reader.dispose();
   if (bi != null) {
     // I am assuming since JBIG2 is always black and white
     // depending on your renderer this might or might be needed
     if (bi.getColorModel().getPixelSize() != bits.intValue()) {
       if (bits.intValue() != 1) {
         LOG.error("Do not know how to deal with JBIG2 with more than 1 bit");
         return;
       }
       BufferedImage packedImage =
           new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
       Graphics graphics = packedImage.getGraphics();
       graphics.drawImage(bi, 0, 0, null);
       graphics.dispose();
       bi = packedImage;
     }
     DataBuffer dBuf = bi.getData().getDataBuffer();
     if (dBuf.getDataType() == DataBuffer.TYPE_BYTE) {
       result.write(((DataBufferByte) dBuf).getData());
     } else {
       LOG.error("Image data buffer not of type byte but type " + dBuf.getDataType());
     }
   } else {
     LOG.error("Something went wrong when decoding the JBIG2 encoded datastream.");
   }
 }
Beispiel #11
0
  @Test
  public void imageReaderTest() throws IOException {
    Iterator<ImageReader> irs = ImageIO.getImageReadersByFormatName("jpg");
    ImageReader imageReader = irs.next();

    ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));

    imageReader.setInput(imageInputStream, true);

    BufferedImage bufferedImage = imageReader.read(0);
    System.out.println(bufferedImage.getWidth());
  }
Beispiel #12
0
 /*
  * 图片裁剪通用接口
  */
 public static void cutImage(String src, String dest, int x, int y, int w, int h)
     throws IOException {
   Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader reader = (ImageReader) iterator.next();
   InputStream in = new FileInputStream(src);
   ImageInputStream iis = ImageIO.createImageInputStream(in);
   reader.setInput(iis, true);
   ImageReadParam param = reader.getDefaultReadParam();
   Rectangle rect = new Rectangle(x, y, w, h);
   param.setSourceRegion(rect);
   BufferedImage bi = reader.read(0, param);
   ImageIO.write(bi, "jpg", new File(dest));
 }
Beispiel #13
0
 /*
  * 图片裁剪二分之一
  */
 public static void cutHalfImage(String src, String dest) throws IOException {
   Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
   ImageReader reader = (ImageReader) iterator.next();
   InputStream in = new FileInputStream(src);
   ImageInputStream iis = ImageIO.createImageInputStream(in);
   reader.setInput(iis, true);
   ImageReadParam param = reader.getDefaultReadParam();
   int imageIndex = 0;
   int width = reader.getWidth(imageIndex) / 2;
   int height = reader.getHeight(imageIndex) / 2;
   Rectangle rect = new Rectangle(width / 2, height / 2, width, height);
   param.setSourceRegion(rect);
   BufferedImage bi = reader.read(0, param);
   ImageIO.write(bi, "jpg", new File(dest));
 }
  public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    readHeader();

    ImageInputStream in = (ImageInputStream) getInput();
    SubImageInputStream sin =
        new SubImageInputStream(in, imageOffsets[imageIndex], imageLengths[imageIndex]);
    sin.seek(0);

    ImageReader ir = new CMYKJPEGImageReader(getOriginatingProvider());
    ir.setInput(sin);

    BufferedImage img = ir.read(0);
    ir.dispose();
    return img;
  }
  /**
   * Load image data for file and put user data attributes into file.
   *
   * @param file File
   * @return true if file image is loaded.
   * @throws java.io.IOException if image can not be loaded
   */
  private static boolean refresh(@NotNull VirtualFile file) throws IOException {
    Long loadedTimeStamp = file.getUserData(TIMESTAMP_KEY);
    SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY);
    if (loadedTimeStamp == null
        || loadedTimeStamp.longValue() != file.getTimeStamp()
        || SoftReference.dereference(imageRef) == null) {
      try {
        final byte[] content = file.contentsToByteArray();

        if (ICO_FORMAT.equalsIgnoreCase(file.getExtension())) {
          try {
            final BufferedImage image =
                ICO_IMAGE_PARSER.getBufferedImage(new ByteSourceArray(content), null);
            file.putUserData(FORMAT_KEY, ICO_FORMAT);
            file.putUserData(BUFFERED_IMAGE_REF_KEY, new SoftReference<>(image));
            return true;
          } catch (ImageReadException ignore) {
          }
        }

        InputStream inputStream = new ByteArrayInputStream(content, 0, content.length);
        ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream);
        try {
          Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
          if (imageReaders.hasNext()) {
            ImageReader imageReader = imageReaders.next();
            try {
              file.putUserData(FORMAT_KEY, imageReader.getFormatName());
              ImageReadParam param = imageReader.getDefaultReadParam();
              imageReader.setInput(imageInputStream, true, true);
              int minIndex = imageReader.getMinIndex();
              BufferedImage image = imageReader.read(minIndex, param);
              file.putUserData(BUFFERED_IMAGE_REF_KEY, new SoftReference<>(image));
              return true;
            } finally {
              imageReader.dispose();
            }
          }
        } finally {
          imageInputStream.close();
        }
      } finally {
        // We perform loading no more needed
        file.putUserData(TIMESTAMP_KEY, file.getTimeStamp());
      }
    }
    return false;
  }
 public Tuple2<BufferedImage, String> readImageAndFormat(InputStream is)
     throws IOException, IllegalArgumentException {
   ImageInputStream iis = ImageIO.createImageInputStream(is);
   Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
   if (!readers.hasNext()) {
     iis.close();
     throw new IllegalArgumentException("unsupported image type");
   }
   ImageReader reader = readers.next();
   String inputFormat = reader.getFormatName();
   reader.setInput(iis, true, true);
   BufferedImage src = reader.read(0);
   reader.dispose();
   iis.close();
   return new Tuple2<BufferedImage, String>(src, inputFormat.toLowerCase());
 }
Beispiel #17
0
  @Test
  public void imageReadParam2() throws IOException {
    Iterator<ImageReader> itr = ImageIO.getImageReadersByFormatName("jpg");
    ImageReader imageReader = itr.next();

    ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));
    imageReader.setInput(imageInputStream, true);

    ImageReadParam imageReadParam = imageReader.getDefaultReadParam();
    imageReadParam.setSourceSubsampling(3, 3, 0, 0);

    BufferedImage bufferedImage = imageReader.read(0, imageReadParam);

    boolean b = ImageIO.write(bufferedImage, "jpg", new File(CONTEXT + "1.jpg"));
    System.out.println(b);
  }
  @Test
  public void test16BitPNG() throws Exception {
    // the resource has been compressed since the palette is way larger than the image itself,
    // and the palette does not get compressed
    InputStream gzippedStream =
        ImageWorkerTest.class.getResource("test-data/sf-sfdem.tif.gz").openStream();
    GZIPInputStream is = new GZIPInputStream(gzippedStream);
    try {
      ImageInputStream iis = ImageIO.createImageInputStream(is);
      ImageReader reader = new TIFFImageReaderSpi().createReaderInstance(iis);
      reader.setInput(iis);
      BufferedImage bi = reader.read(0);
      reader.dispose();
      iis.close();
      IndexColorModel icm = (IndexColorModel) bi.getColorModel();
      assertEquals(65536, icm.getMapSize());

      final File outFile = TestData.temp(this, "temp.png");
      ImageWorker worker = new ImageWorker(bi);
      worker.writePNG(outFile, "FILTERED", 0.75f, true, false);
      worker.dispose();

      // make sure we can read it
      BufferedImage back = ImageIO.read(outFile);

      // we expect a RGB one
      ComponentColorModel ccm = (ComponentColorModel) back.getColorModel();
      assertEquals(3, ccm.getNumColorComponents());

      // now ask to write paletted
      worker = new ImageWorker(bi);
      worker.writePNG(outFile, "FILTERED", 0.75f, true, true);
      worker.dispose();

      // make sure we can read it
      back = ImageIO.read(outFile);

      // we expect a RGB one
      icm = (IndexColorModel) back.getColorModel();
      assertEquals(3, icm.getNumColorComponents());
      assertTrue(icm.getMapSize() <= 256);
    } finally {
      is.close();
    }
  }
  /**
   * Creates a scaled version of the image provided by the specified input stream. This method tries
   * to use thumbnails in the original image: If none fits, the full image is read and scaled.
   */
  public static BufferedImage createScaledImage(
      InputStream aInputStream, int aMaxSize, boolean aWithAlpha, Object aInterpolationQuality)
      throws IOException {
    ImageInputStream theImageInputStream = ImageIO.createImageInputStream(aInputStream);
    Iterator<ImageReader> theImageReaders = ImageIO.getImageReaders(theImageInputStream);

    ImageReader theReader;
    if (theImageReaders.hasNext()) theReader = theImageReaders.next();
    else return null;

    theReader.setInput(theImageInputStream);

    BufferedImage theOriginalImage = null;
    if (theReader.readerSupportsThumbnails()) {
      // Find the most suitable thumbnail, ie. the smallest that is bigger than requested size.
      int theThumbnailsCount = theReader.getNumThumbnails(0);
      int theFittest = -1; // Which is the fittest thumbnail?
      int theFittestScore = Integer.MAX_VALUE; // Score of the current fittest. Lower is better.

      for (int i = 0; i < theThumbnailsCount; i++) {
        int theW = theReader.getThumbnailWidth(0, i);
        int theH = theReader.getThumbnailHeight(0, i);

        int theScore;
        if (theW < aMaxSize & theH < aMaxSize) theScore = Integer.MAX_VALUE;
        else theScore = Math.max(theW, theH) - aMaxSize;

        if (theScore < theFittestScore) {
          theFittest = i;
          theFittestScore = theScore;
          if (theScore == 0) break; // Can't improve, so don't iterate any more.
        }
      }

      // Get the thumbnail
      if (theFittest >= 0) theOriginalImage = theReader.readThumbnail(0, theFittest);
    }

    // Fallback if no thumbnail is found
    if (theOriginalImage == null) theOriginalImage = theReader.read(0);

    return createScaledImage(theOriginalImage, aMaxSize, aWithAlpha, aInterpolationQuality);
  }
  private BufferedImage readImage() {
    Iterator<?> readersIterator = ImageIO.getImageReadersByMIMEType(fieldImageMineType);

    if (readersIterator.hasNext()) {
      ImageReader reader = (ImageReader) readersIterator.next();

      reader.setInput(
          new MemoryCacheImageInputStream(new ByteArrayInputStream(fieldOriginal)), true, true);

      try {
        BufferedImage image = reader.read(0);
        return image;
      } catch (Throwable th) {
        new JLogMessage(JLogLevel.ERROR, "Fiction book image {0} cannot be decoded")
            .log(th, getImageFileName());
      }
    }
    return null;
  }
Beispiel #21
0
  @Test
  public void imageReadParam() throws IOException {
    Iterator<ImageReader> itr = ImageIO.getImageReadersByFormatName("jpg");
    ImageReader imageReader = itr.next();

    ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG));

    imageReader.setInput(imageInputStream, true);

    ImageReadParam imageReadParam = imageReader.getDefaultReadParam();
    int halfWidth = imageReader.getWidth(0) / 2;
    int halfHeight = imageReader.getHeight(0) / 2;
    Rectangle rectangle = new Rectangle(0, 0, halfWidth, halfHeight);
    imageReadParam.setSourceRegion(rectangle);

    BufferedImage bufferedImage = imageReader.read(0, imageReadParam);
    System.out.println(bufferedImage.getWidth());

    boolean result = ImageIO.write(bufferedImage, "png", new File(CONTEXT + "999.png"));
    System.out.println(result);
  }
  @Test
  public void test16BitGIF() throws Exception {
    // the resource has been compressed since the palette is way larger than the image itself,
    // and the palette does not get compressed
    InputStream gzippedStream =
        ImageWorkerTest.class.getResource("test-data/sf-sfdem.tif.gz").openStream();
    GZIPInputStream is = new GZIPInputStream(gzippedStream);
    try {
      ImageInputStream iis = ImageIO.createImageInputStream(is);
      ImageReader reader = new TIFFImageReaderSpi().createReaderInstance(iis);
      reader.setInput(iis);
      BufferedImage bi = reader.read(0);
      if (TestData.isInteractiveTest()) {
        ImageIOUtilities.visualize(bi, "before");
      }
      reader.dispose();
      iis.close();
      IndexColorModel icm = (IndexColorModel) bi.getColorModel();
      assertEquals(65536, icm.getMapSize());

      final File outFile = TestData.temp(this, "temp.gif");
      ImageWorker worker = new ImageWorker(bi);
      worker.writeGIF(outFile, "LZW", 0.75f);

      // Read it back.
      bi = ImageIO.read(outFile);
      if (TestData.isInteractiveTest()) {
        ImageIOUtilities.visualize(bi, "after");
      }
      ColorModel cm = bi.getColorModel();
      assertTrue("wrong color model", cm instanceof IndexColorModel);
      assertEquals("wrong transparency model", Transparency.OPAQUE, cm.getTransparency());
      final IndexColorModel indexColorModel = (IndexColorModel) cm;
      assertEquals("wrong transparent color index", -1, indexColorModel.getTransparentPixel());
      assertEquals("wrong component size", 8, indexColorModel.getComponentSize(0));
      outFile.delete();
    } finally {
      is.close();
    }
  }
Beispiel #23
0
  /**
   * 图片截取
   *
   * @param file
   * @param newName
   * @param path
   * @param x
   * @param y
   * @param width
   * @param height
   * @return author:caobo date:Oct 14, 2009 12:38:05 PM
   */
  public static File cutting(
      File file, String newName, String path, int x, int y, int width, int height) {
    ImageOutputStream out = null;
    InputStream is = null;
    ImageInputStream iis = null;
    try {
      String endName = file.getName();
      endName = endName.substring(endName.lastIndexOf(".") + 1);
      Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(endName);
      ImageReader reader = (ImageReader) readers.next();
      is = new FileInputStream(file);
      iis = ImageIO.createImageInputStream(is);
      reader.setInput(iis, true);

      ImageReadParam param = reader.getDefaultReadParam();
      Rectangle rect = new Rectangle(x, y, width, height);
      param.setSourceRegion(rect);
      BufferedImage bi = reader.read(0, param);
      File newFile = new File(path);

      if (!newFile.exists()) newFile.mkdirs();
      newFile = new File(path, newName);
      out = ImageIO.createImageOutputStream(new FileOutputStream(newFile));
      ImageIO.write(bi, endName, out);
      file = newFile;
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        iis.close();
        is.close();
        out.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return file;
  }
  private BufferedImage scaleDown(
      final ImageInputStream inputStream, final int maxWidth, final int maxHeight)
      throws IOException {
    final Iterator<ImageReader> readers = ImageIO.getImageReaders(inputStream);
    if (!readers.hasNext()) {
      throw new IOException("No ImageReader available for the given ImageInputStream");
    }
    // Use the first reader, next will instantiate ImageReader which needs to be disposed
    final ImageReader reader = readers.next();
    try {
      final ImageReadParam param = reader.getDefaultReadParam();
      reader.setInput(inputStream);

      final Dimension original = new Dimension(reader.getWidth(0), reader.getHeight(0));
      final Dimension target = new Dimension(maxWidth, maxHeight);
      final int ratio = maintainAspectRatio(original, target);
      param.setSourceSubsampling(ratio, ratio, 0, 0);

      return reader.read(0, param);
    } finally {
      reader.dispose();
    }
  }
Beispiel #25
0
  /**
   * 1、�?过ImageIO获得ImageWriter对象 2、�?过ImageIO获得ImageOutputStream对象
   * 3、�?过给定的ImageOutputStream设定ImageWriter的输出源 4、写图片
   *
   * @throws IOException
   */
  @Test
  public void teatImageWriter() throws IOException {

    // ~:指定配置imageReader
    Iterator<ImageReader> itrReads = ImageIO.getImageReadersByFormatName("png");
    ImageReader imageReader = itrReads.next();
    ImageInputStream imageInputSteam =
        ImageIO.createImageInputStream(new File(CONTEXT + "999.png"));
    imageReader.setInput(imageInputSteam, true);
    // ~~

    BufferedImage bufferedImage = imageReader.read(0);

    // ~:指定配置imageWriter
    Iterator<ImageWriter> itr = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter imageWriter = itr.next();

    ImageOutputStream imageOutputStream =
        ImageIO.createImageOutputStream(new File(CONTEXT + "213.jpg"));
    imageWriter.setOutput(imageOutputStream);
    // ~~

    imageWriter.write(bufferedImage);
  }
    static BufferedImage readImage(final byte[] bytes) {
      // Wrap ImageInputStream around the bytes.  We could use MemoryCacheImageInputStream but it
      // will
      // cache the data which is quite unnecessary given we have it all in-memory already.
      ImageInputStream imageInputStream =
          new ImageInputStreamImpl() {
            // TODO re-use this instance; superclass has 8KB buffer.

            @Override
            public int read() throws IOException {
              checkClosed();
              bitOffset = 0;
              if (streamPos >= bytes.length) {
                return -1;
              } else {
                return bytes[(int) streamPos++];
              }
            }

            @Override
            public int read(byte[] b, int off, int len) throws IOException {
              checkClosed();
              bitOffset = 0;
              if (streamPos >= bytes.length) {
                return -1;
              } else {
                int copyLen = Math.min(len, bytes.length - (int) streamPos);
                System.arraycopy(bytes, (int) streamPos, b, off, copyLen);
                streamPos += copyLen;
                return copyLen;
              }
            }

            @Override
            public long length() {
              return bytes.length;
            }

            @Override
            public boolean isCached() {
              return true;
            }

            @Override
            public boolean isCachedMemory() {
              return true;
            }
          };
      try {
        // TODO can/should we re-use an imageReader instance on FacetInfo?
        ImageReader imageReader = imageReaderSpi.createReaderInstance();

        imageReader.setInput(
            imageInputStream,
            false, // forwardOnly
            true); // ignoreMetadata
        return imageReader.read(0); // read first & only image
      } catch (IOException e) {
        throw new SolrException(
            SolrException.ErrorCode.SERVER_ERROR, "Problem reading png heatmap: " + e);
      }
    }
Beispiel #27
0
 /**
  * Parses teh TIFF contained in the response as a {@link RenderedImage}
  *
  * @param response
  * @return
  * @throws IOException
  */
 RenderedImage readTiff(MockHttpServletResponse response) throws IOException {
   ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
   reader.setInput(ImageIO.createImageInputStream(getBinaryInputStream(response)));
   return reader.read(0);
 }
Beispiel #28
0
  /**
   * 根据指定坐标和长宽裁剪图片
   *
   * @param inputFilePath 源图片
   * @param outputFilePath 产生新图片路径
   * @param x x轴的开始坐标
   * @param y y轴的开始坐标
   * @param width 所裁剪的宽度
   * @param height 所裁剪的高度
   */
  public static void cut(
      String inputFilePath, String outputFilePath, int x, int y, int width, int height) {

    FileInputStream fileInputStream = null;
    ImageInputStream imageInputStream = null;
    try {
      // 获得源文件
      File inputFile = new File(inputFilePath);
      if (!inputFile.exists()) {
        logger.fatal(new FileNotFoundException());
        return;
      }

      // 读取图片文件
      fileInputStream = new FileInputStream(inputFilePath);

      String format = FileUtil.getFileSuffix(inputFilePath);
      // System.out.println(format);
      // ImageReader声称能够解码指定格式
      Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(format);
      ImageReader reader = it.next();

      // 获取图片流
      imageInputStream = ImageIO.createImageInputStream(fileInputStream);

      // 输入源中的图像将只按顺序读取
      reader.setInput(imageInputStream, true);

      // 描述如何对流进行解码
      ImageReadParam param = reader.getDefaultReadParam();

      // 图片裁剪区域
      Rectangle rect = new Rectangle(x, y, width, height);

      // 提供一个 BufferedImage,将其用作解码像素数据的目标
      param.setSourceRegion(rect);

      // 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象
      BufferedImage bi = reader.read(0, param);

      // 保存新图片
      // File tempOutFile = new File(outputFilePath);
      // if (!tempOutFile.exists()) {
      // tempOutFile.mkdirs();
      // }
      ImageIO.write(bi, format, new File(outputFilePath));
    } catch (Exception e) {
      e.printStackTrace();
      logger.fatal(e);
    } finally {
      try {
        if (fileInputStream != null) {
          fileInputStream.close();
        }
        if (imageInputStream != null) {
          imageInputStream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
        logger.fatal(e);
      }
    }
  }