コード例 #1
0
ファイル: VisualOutput.java プロジェクト: SGGames/xxl
 /**
  * replaces the current output image by the top of the image stack and removes the top of the
  * stack
  */
 public void pop() {
   try {
     content.setData(imageStack.pop());
   } catch (EmptyStackException e) {
     clear();
   }
 }
コード例 #2
0
ファイル: GdalDataset.java プロジェクト: deegree/deegree3
 private BufferedImage toImage(byte[][] bands, int xSize, int ySize) {
   int numberOfBands = bands.length;
   int numBytes = xSize * ySize * numberOfBands;
   DataBuffer imgBuffer = new DataBufferByte(bands, numBytes);
   SampleModel sampleModel = new BandedSampleModel(TYPE_BYTE, xSize, ySize, numberOfBands);
   WritableRaster raster = Raster.createWritableRaster(sampleModel, imgBuffer, null);
   if (numberOfBands == 1) {
     Band band = dataset.GetRasterBand(1);
     int bufType = band.getDataType();
     int dataType = detectDataType(band, bufType);
     BufferedImage img;
     if (BufferedImage.TYPE_BYTE_INDEXED == dataType) {
       ColorTable ct = band.GetRasterColorTable();
       IndexColorModel cm = ct.getIndexColorModel(gdal.GetDataTypeSize(bufType));
       img = new BufferedImage(xSize, ySize, dataType, cm);
     } else {
       img = new BufferedImage(xSize, ySize, dataType);
     }
     img.setData(raster);
     return img;
   }
   ColorSpace cs = ColorSpace.getInstance(CS_sRGB);
   ColorModel cm;
   if (numberOfBands == 3) {
     cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, TYPE_BYTE);
   } else if (numberOfBands == 4) {
     cm = new ComponentColorModel(cs, true, false, ColorModel.TRANSLUCENT, TYPE_BYTE);
   } else {
     throw new IllegalArgumentException("Unsupported number of bands: " + numberOfBands);
   }
   return new BufferedImage(cm, raster, false, null);
 }
コード例 #3
0
ファイル: AddeImagePreview.java プロジェクト: ethanrd/IDV
 /**
  * _more_
  *
  * @param image_data _more_
  */
 private void createBufferedImage(float image_data[][]) {
   WritableRaster raster = null;
   int num_bands = 0;
   if (null != preview_image) {
     preview_image.getSampleModel().getNumBands();
   }
   if ((null == preview_image) || (image_data.length != num_bands)) {
     if (image_data.length == 1) {
       preview_image =
           new BufferedImage(subSampledPixels, subSampledScans, BufferedImage.TYPE_BYTE_GRAY);
     } else {
       preview_image =
           new BufferedImage(subSampledPixels, subSampledScans, BufferedImage.TYPE_3BYTE_BGR);
     }
     DataBufferFloat dbuf =
         new DataBufferFloat(image_data, subSampledPixels * subSampledScans * image_data.length);
     SampleModel sampleModel =
         new BandedSampleModel(0, subSampledPixels, subSampledScans, image_data.length);
     raster = Raster.createWritableRaster(sampleModel, dbuf, new Point(0, 0));
     preview_image.setData(raster);
   } else if (1 == num_bands) {
     preview_image
         .getRaster()
         .setDataElements(
             0, 0, preview_image.getWidth(), preview_image.getHeight(), image_data[0]);
   } else if (3 == num_bands) {
     preview_image
         .getRaster()
         .setDataElements(0, 0, preview_image.getWidth(), preview_image.getHeight(), image_data);
   }
 }
コード例 #4
0
ファイル: Tester.java プロジェクト: hillst/PhenoFront
  /**
   * We need to figure out how to get more than just vis images :/
   *
   * @param args
   * @throws IOException
   * @throws ZipException
   */
  public static void dumb(String[] args) throws IOException, ZipException {
    /**
     * Things to try, only look at first 14 bits (???) only look at last 14 bits (???) extrapolate
     * 14 bits into 16 bit space
     */

    // old stuff
    String filename = "/data/pgftp/LemnaTest/2013-11-06/blob212853";
    int width = 1388;
    int height = 1038;
    // some shit i copied on the internet
    byte[] spot =
        IOUtils.toByteArray(
            new FileInputStream("/Users/shill/Documents/JSEE_workspace/PhenoFront/lib/data"));
    short[] pixelArray = toShorts(spot);
    // foreach short, value of

    Point origin = new Point();
    DataBufferUShort dataBuffer = new DataBufferUShort(pixelArray, (width * height), 0);
    int[] bandOffets = {0};
    ComponentSampleModel sampleModel =
        new ComponentSampleModel(DataBuffer.TYPE_USHORT, width, height, 1, width, bandOffets);
    WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, origin);

    BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY);
    buffImg.setData(raster);
    ImageIO.write(
        buffImg, "tiff", new File("/Users/shill/Documents/JSEE_workspace/PhenoFront/lib/b.tiff"));
  }
コード例 #5
0
ファイル: JBIG2Decoder.java プロジェクト: Z-z-z-z/PDFrenderer
  /**
   * @param page
   * @return
   */
  public BufferedImage getPageAsBufferedImage(int page) {
    page++;
    JBIG2Bitmap pageBitmap = streamDecoder.findPageSegement(page).getPageBitmap();

    byte[] bytes = pageBitmap.getData(true);

    if (bytes == null) return null;

    // make a a DEEP copy so we cant alter
    int len = bytes.length;
    byte[] copy = new byte[len];
    System.arraycopy(bytes, 0, copy, 0, len);

    // byte[] data = pageBitmap.getData(true).clone();
    int width = pageBitmap.getWidth();
    int height = pageBitmap.getHeight();

    /** create an image from the raw data */
    DataBuffer db = new DataBufferByte(copy, copy.length);

    WritableRaster raster = Raster.createPackedRaster(db, width, height, 1, null);
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
    image.setData(raster);

    return image;
  }
コード例 #6
0
ファイル: VisualOutput.java プロジェクト: SGGames/xxl
 /**
  * replaces the current output image by the top of the image stack without removing the top of the
  * stack
  */
 public void peek() {
   try {
     content.setData(imageStack.peek());
   } catch (EmptyStackException e) {
     clear();
   }
   repaint();
 }
コード例 #7
0
ファイル: GIFReader.java プロジェクト: kushalkantgoyal/icafe
  /**
   * Gets the current frame as a BufferedImage the same size as the logical screen. Graphic Control
   * Extension and Image Descriptor parameters are taken into account When creating the frame. The
   * resulting frame is actually a "composite" one or a snapshot as seen in an animated GIF. Such
   * frames may not be the same as the frames created by {@link
   * #getFrameAsBufferedImage(InputStream) getFrameAsBufferedImage} which could be of different
   * sizes and may also have to rely on the previous frames to look the same as the frames created
   * here.
   *
   * <p>Note: do not mix this method with {@link #read(InputStream) read} or {@link
   * #getFrameAsBufferedImage(InputStream) getFrameAsBufferedImage}. Use them separately.
   *
   * @param is input stream for the image - single frame or multiple frame animated GIF
   * @return java BufferedImage or null if there is no more frames
   * @throws Exception
   */
  protected BufferedImage getFrameAsBufferedImageEx(InputStream is) throws Exception {
    // This single call will trigger the reading of the global scope data
    BufferedImage bi = getFrameAsBufferedImage(is);
    if (bi == null) return null;
    int maxWidth = (width < logicalScreenWidth) ? width : logicalScreenWidth;
    int maxHeight = (height < logicalScreenHeight) ? height : logicalScreenHeight;
    if (baseImage == null)
      baseImage =
          new BufferedImage(logicalScreenWidth, logicalScreenHeight, BufferedImage.TYPE_INT_ARGB);
    Rectangle area = new Rectangle(image_x, image_y, maxWidth, maxHeight);
    // Create a backup bufferedImage from the base image for the area of the current frame
    BufferedImage backup = new BufferedImage(maxWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
    backup.setData(baseImage.getData(area));
    /* End of backup */
    Graphics2D g = baseImage.createGraphics();
    // Draw this frame to the base
    g.drawImage(bi, image_x, image_y, null);
    // We need to clone the base image since we are going to dispose it later according to the
    // disposal method
    BufferedImage clone =
        new BufferedImage(logicalScreenWidth, logicalScreenHeight, BufferedImage.TYPE_INT_ARGB);
    clone.setData(baseImage.getData());
    // Check about disposal method to take action accordingly
    if (disposalMethod == 1 || disposalMethod == 0) // Leave in place or unspecified
    ; // No action needed
    else if (disposalMethod == 2) { // Restore to background
      Composite oldComposite = g.getComposite();
      g.setComposite(AlphaComposite.Clear);
      g.fillRect(image_x, image_y, width, height);
      g.setComposite(oldComposite);
    } else if (disposalMethod == 3) { // Restore to previous
      Composite oldComposite = g.getComposite();
      g.setComposite(AlphaComposite.Src);
      g.drawImage(backup, image_x, image_y, null);
      g.setComposite(oldComposite);
    } else { // To be defined - should never come here
      baseImage =
          new BufferedImage(logicalScreenWidth, logicalScreenHeight, BufferedImage.TYPE_INT_ARGB);
      g = baseImage.createGraphics();
    }

    return clone;
  }
コード例 #8
0
  public static BufferedImage bufferedImageFromByteArrayJpeg(
      ColorModel colorModel, byte[] payload, int width, int height) {
    BufferedImage ret = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    DataBuffer dataBuffer = new DataBufferByte(payload, payload.length, 0);
    SampleModel sampleModel = colorModel.createCompatibleSampleModel(width, height);

    WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, null);
    ret.setData(raster);

    return ret;
  }
コード例 #9
0
  @Override
  protected BufferedImage loadImage(int imageIndex) throws IOException {
    checkImageIndex(imageIndex);
    ensureMetadataIsLoaded(imageIndex);

    final WritableRaster raster = loadRAWRaster();
    final int width = raster.getWidth();
    final int height = raster.getHeight();

    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY);
    bufferedImage.setData(raster);

    return bufferedImage;
  }
コード例 #10
0
  @Test
  public void test4BitPNG() throws Exception {

    // create test image
    IndexColorModel icm =
        new IndexColorModel(
            4,
            16,
            new byte[] {(byte) 255, 0, 0, 0, 16, 32, 64, (byte) 128, 1, 2, 3, 4, 5, 6, 7, 8},
            new byte[] {0, (byte) 255, 0, 0, 16, 32, 64, (byte) 128, 1, 2, 3, 4, 5, 6, 7, 8},
            new byte[] {0, 0, (byte) 255, 0, 16, 32, 64, (byte) 128, 1, 2, 3, 4, 5, 6, 7, 8});
    assertEquals(16, icm.getMapSize());

    // create random data
    WritableRaster data =
        com.sun.media.jai.codecimpl.util.RasterFactory.createWritableRaster(
            icm.createCompatibleSampleModel(32, 32), new Point(0, 0));
    for (int x = data.getMinX(); x < data.getMinX() + data.getWidth(); x++) {
      for (int y = data.getMinY(); y < data.getMinY() + data.getHeight(); y++) {
        data.setSample(x, y, 0, (x + y) % 8);
      }
    }

    final BufferedImage bi = new BufferedImage(icm, data, false, null);
    assertEquals(16, ((IndexColorModel) bi.getColorModel()).getMapSize());
    assertEquals(4, bi.getSampleModel().getSampleSize(0));
    bi.setData(data);
    if (TestData.isInteractiveTest()) {
      ImageIOUtilities.visualize(bi, "before");
    }

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

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

    // we expect an IndexColorMolde one matching the old one
    IndexColorModel ccm = (IndexColorModel) back.getColorModel();
    assertEquals(3, ccm.getNumColorComponents());
    assertEquals(16, ccm.getMapSize());
    assertEquals(4, ccm.getPixelSize());
    if (TestData.isInteractiveTest()) {
      ImageIOUtilities.visualize(back, "after");
    }
  }
コード例 #11
0
  public static BufferedImage bufferedImageFromRosMessageRaw(
      ColorModel colorModel, sensor_msgs.Image imageMessage) {
    int width = imageMessage.getWidth();
    int height = imageMessage.getHeight();

    byte[] payload = imageMessage.getData().array();
    BufferedImage ret = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    DataBuffer dataBuffer =
        new DataBufferByte(payload, payload.length, imageMessage.getData().arrayOffset());
    SampleModel sampleModel = colorModel.createCompatibleSampleModel(width, height);

    WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, null);
    ret.setData(raster);

    return ret;
  }
コード例 #12
0
  public static BufferedImage make(
      int w, int h, byte[] data, final GenericColorSpace decodeColorData, int d) {

    final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY);

    final DataBuffer db = new DataBufferByte(data, data.length);
    // needs to be inverted in this case (ie 12dec/mariners_annual_2012.pdf)
    if (decodeColorData.getID() == ColorSpaces.Separation) {
      final int count = data.length;
      for (int aa = 0; aa < count; aa++) {
        data[aa] = (byte) (data[aa] ^ 255);
      }
    }

    final WritableRaster raster = Raster.createPackedRaster(db, w, h, d, null);
    image.setData(raster);

    return image;
  }
コード例 #13
0
ファイル: CCannyEdgeDetector.java プロジェクト: m3art/fresco
  @Override
  protected BufferedImage doInBackground() {
    int x, y, b;
    int[] A = null;
    int[] sum = new int[bands], sum_x = new int[bands], sum_y = new int[bands];
    WritableRaster raster = image.getRaster();

    for (x = 0; x < size.getWidth(); x++) {
      for (y = 0; y < size.getHeight(); y++) {
        if (y == 0 || y == size.getHeight() - 1 || x == 0 || x == size.getWidth() - 1) {
          for (b = 0; b < bands; b++) {
            sum[b] = 0;
          }
        } else {
          for (b = 0; b < bands; b++) {
            A =
                input.getSamples(
                    x - 1, y - 1, CSobelOperator.matrix_size, CSobelOperator.matrix_size, b, A);
            sum_x[b] = CSobelOperator.getGx(A);
            sum_y[b] = CSobelOperator.getGy(A);
          }

          for (b = 0; b < bands; b++) {
            sum[b] = Math.abs(sum_x[b]) + Math.abs(sum_y[b]);
          }
        }
        raster.setPixel(x, y, sum);
        setProgress(
            100
                * (x * ((int) size.getHeight()) + y)
                / ((int) (size.getWidth() * size.getHeight())));
      }
    }
    image.setData(raster);
    return image;
  }
コード例 #14
0
 public void updateImage(BufferedImage rImage) {
   bImage.setData(rImage.getRaster());
   repaint();
 }
コード例 #15
0
  private static BufferedImage scaleImage(Raster ras, int pX, int pY, int comp, int d) {

    int w = ras.getWidth();
    int h = ras.getHeight();

    byte[] data = ((DataBufferByte) ras.getDataBuffer()).getData();

    // see what we could reduce to and still be big enough for page
    int newW = w, newH = h;

    int sampling = 1;
    int smallestH = pY << 2; // double so comparison works
    int smallestW = pX << 2;

    // cannot be smaller than page
    while (newW > smallestW && newH > smallestH) {
      sampling = sampling << 1;
      newW = newW >> 1;
      newH = newH >> 1;
    }

    int scaleX = w / pX;
    if (scaleX < 1) scaleX = 1;

    int scaleY = h / pY;
    if (scaleY < 1) scaleY = 1;

    // choose smaller value so at least size of page
    sampling = scaleX;
    if (sampling > scaleY) sampling = scaleY;

    // switch to 8 bit and reduce bw image size by averaging
    if (sampling > 1) {

      newW = w / sampling;
      newH = h / sampling;

      if (d == 1) {

        int size = newW * newH;

        byte[] newData = new byte[size];

        final int[] flag = {1, 2, 4, 8, 16, 32, 64, 128};

        int origLineLength = (w + 7) >> 3;

        int bit;
        byte currentByte;

        // scan all pixels and down-sample
        for (int y = 0; y < newH; y++) {
          for (int x = 0; x < newW; x++) {

            int bytes = 0, count = 0;

            // allow for edges in number of pixels left
            int wCount = sampling, hCount = sampling;
            int wGapLeft = w - x;
            int hGapLeft = h - y;
            if (wCount > wGapLeft) wCount = wGapLeft;
            if (hCount > hGapLeft) hCount = hGapLeft;

            // count pixels in sample we will make into a pixel (ie
            // 2x2 is 4 pixels , 4x4 is 16 pixels)
            for (int yy = 0; yy < hCount; yy++) {
              for (int xx = 0; xx < wCount; xx++) {

                currentByte =
                    data[((yy + (y * sampling)) * origLineLength) + (((x * sampling) + xx) >> 3)];

                bit = currentByte & flag[7 - (((x * sampling) + xx) & 7)];

                if (bit != 0) bytes++;
                count++;
              }
            }

            // set value as white or average of pixels
            int offset = x + (newW * y);
            if (count > 0) {
              newData[offset] = (byte) ((255 * bytes) / count);
            } else {
              newData[offset] = (byte) 255;
            }
          }
        }

        data = newData;

        h = newH;
        w = newW;
        d = 8;

        // imageMask=false;

      } else if (d == 8) {

        int x = 0, y = 0, xx = 0, yy = 0, jj = 0, origLineLength = 0;
        try {

          // black and white
          if (w * h == data.length) comp = 1;

          byte[] newData = new byte[newW * newH * comp];

          // System.err.println(w+" "+h+" "+data.length+"
          // comp="+comp+" scaling="+sampling+" "+decodeColorData);

          origLineLength = w * comp;

          // System.err.println("size="+w*h*comp+" filter"+filter+"
          // scaling="+sampling+" comp="+comp);
          // System.err.println("w="+w+" h="+h+" data="+data.length+"
          // origLineLength="+origLineLength+" sampling="+sampling);
          // scan all pixels and down-sample
          for (y = 0; y < newH; y++) {
            for (x = 0; x < newW; x++) {

              // allow for edges in number of pixels left
              int wCount = sampling, hCount = sampling;
              int wGapLeft = w - x;
              int hGapLeft = h - y;
              if (wCount > wGapLeft) wCount = wGapLeft;
              if (hCount > hGapLeft) hCount = hGapLeft;

              for (jj = 0; jj < comp; jj++) {
                int byteTotal = 0, count = 0;
                // count pixels in sample we will make into a
                // pixel (ie 2x2 is 4 pixels , 4x4 is 16 pixels)
                for (yy = 0; yy < hCount; yy++) {
                  for (xx = 0; xx < wCount; xx++) {

                    byteTotal =
                        byteTotal
                            + (data[
                                    ((yy + (y * sampling)) * origLineLength)
                                        + (((x * sampling * comp) + (xx * comp) + jj))]
                                & 255);

                    count++;
                  }
                }

                // set value as white or average of pixels
                if (count > 0)
                  // if(index==null)
                  newData[jj + (x * comp) + (newW * y * comp)] = (byte) ((byteTotal) / count);
                // else
                // newData[x+(newW*y)]=(byte)(((index[1] &
                // 255)*byteTotal)/count);
                else {
                  // if(index==null)
                  // newData[jj+x+(newW*y*comp)]=(byte) 255;
                  // else
                  // newData[x+(newW*y)]=index[0];
                }
              }
            }
          }

          data = newData;
          h = newH;
          w = newW;

        } catch (Exception e) {

          // <start-full><start-demo>
          System.err.println(
              "xx="
                  + xx
                  + " yy="
                  + yy
                  + " jj="
                  + jj
                  + " ptr="
                  + ((yy + (y * sampling)) * origLineLength)
                  + (((x * sampling) + (xx * comp) + jj))
                  + '/'
                  + data.length);

          // System.err.println("index="+index);
          System.err.println(
              ((yy + (y * sampling)) * origLineLength)
                  + " "
                  + (((x * sampling) + (xx * comp) + jj)));
          System.err.println(
              "w=" + w + " h=" + h + " sampling=" + sampling + " x=" + x + " y=" + y);
          // System.out.println("xx="+xx+" yy="+yy);
          e.printStackTrace();
          // <end-demo><end-full>
        }
      }
    }

    if (sampling > 1) {
      final int[] bands = {0};

      // System.out.println("w=" + w + " h=" + h + " size=" +
      // data.length);
      // WritableRaster raster =Raster.createPackedRaster(new
      // DataBufferByte(newData, newData.length), newW, newH, 1, null);
      Raster raster =
          Raster.createInterleavedRaster(
              new DataBufferByte(data, data.length), w, h, w, 1, bands, null);

      BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
      image.setData(raster);

      return image;
    } else {
      return null;
    }
  }
コード例 #16
0
ファイル: CA.java プロジェクト: jkwhite/nausicaa
 public void setData(Raster r) {
   _i.setData(r);
 }
コード例 #17
0
  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();
    }
  }
コード例 #18
0
  @Override
  protected boolean loadTexture(TextureTile tile, URL textureURL) {
    if (!(tile instanceof MinMaxTextureTile)) {
      Logging.logger().severe("Tile is not instance of " + MinMaxTextureTile.class);
      getLevels().markResourceAbsent(tile);
      return false;
    }

    synchronized (fileLock) {
      InputStream is = null;
      try {
        is = textureURL.openStream();
        DataInputStream dis = new DataInputStream(is);

        int width = dis.readInt();
        int height = dis.readInt();
        int bands = dis.readInt();
        double minElevation = dis.readDouble();
        double maxElevation = dis.readDouble();
        byte[][] bytes = new byte[bands][];
        for (int i = 0; i < bands; i++) {
          bytes[i] = new byte[width * height];
          is.read(bytes[i]);
        }

        DataBuffer db = new DataBufferByte(bytes, width * height);
        SampleModel sm = new BandedSampleModel(DataBuffer.TYPE_BYTE, width, height, bands);
        Raster raster = Raster.createRaster(sm, db, null);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
        image.setData(raster);

        TextureData textureData = TextureIO.newTextureData(image, isUseMipMaps());
        if (textureData == null) {
          throw new Exception("Could not create texture data for " + textureURL);
        }

        ((MinMaxTextureTile) tile).setMinElevation(minElevation);
        ((MinMaxTextureTile) tile).setMaxElevation(maxElevation);
        tile.setTextureData(textureData);

        // if (tile.getLevelNumber() != 0 || !this.isRetainLevelZeroTiles())
        addTileToCache(tile);

        getLevels().unmarkResourceAbsent(tile);
        firePropertyChange(AVKey.LAYER, null, this);
        return true;
      } catch (Exception e) {
        // Assume that something's wrong with the file and delete it.
        gov.nasa.worldwind.WorldWind.getDataFileStore().removeFile(textureURL);
        getLevels().markResourceAbsent(tile);
        String message = Logging.getMessage("generic.DeletedCorruptDataFile", textureURL);
        Logging.logger().info(message + ":" + e.getLocalizedMessage());
        return false;
      } finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
          }
        }
      }
    }
  }
コード例 #19
0
ファイル: PDFImage.java プロジェクト: ryohang/PDFrenderer
  /**
   * Parse the image stream into a buffered image. Note that this is guaranteed to be called after
   * all the other setXXX methods have been called.
   *
   * <p>NOTE: the color convolving is extremely slow on large images. It would be good to see if it
   * could be moved out into the rendering phases, where we might be able to scale the image down
   * first.</p
   */
  protected BufferedImage parseData(byte[] data) {
    // create the data buffer
    DataBuffer db = new DataBufferByte(data, data.length);

    // pick a color model, based on the number of components and
    // bits per component
    ColorModel cm = getColorModel();

    // create a compatible raster
    SampleModel sm = cm.createCompatibleSampleModel(getWidth(), getHeight());
    WritableRaster raster;
    try {
      raster = Raster.createWritableRaster(sm, db, new Point(0, 0));
    } catch (RasterFormatException e) {
      int tempExpectedSize =
          getWidth()
              * getHeight()
              * getColorSpace().getNumComponents()
              * Math.max(8, getBitsPerComponent())
              / 8;

      if (tempExpectedSize < 3) {
        tempExpectedSize = 3;
      }
      if (tempExpectedSize > data.length) {
        byte[] tempLargerData = new byte[tempExpectedSize];
        System.arraycopy(data, 0, tempLargerData, 0, data.length);
        db = new DataBufferByte(tempLargerData, tempExpectedSize);
        raster = Raster.createWritableRaster(sm, db, new Point(0, 0));
      } else {
        throw e;
      }
    }

    /*
     * Workaround for a bug on the Mac -- a class cast exception in
     * drawImage() due to the wrong data buffer type (?)
     */
    BufferedImage bi = null;
    if (cm instanceof IndexColorModel) {
      IndexColorModel icm = (IndexColorModel) cm;

      // choose the image type based on the size
      int type = BufferedImage.TYPE_BYTE_BINARY;
      if (getBitsPerComponent() == 8) {
        type = BufferedImage.TYPE_BYTE_INDEXED;
      }

      // create the image with an explicit indexed color model.
      bi = new BufferedImage(getWidth(), getHeight(), type, icm);

      // set the data explicitly as well
      bi.setData(raster);
    } else {
      // Raster is already in a format which is supported by Java2D,
      // such as RGB or Gray.
      bi = new BufferedImage(cm, raster, true, null);
    }

    // hack to avoid *very* slow conversion
    ColorSpace cs = cm.getColorSpace();
    ColorSpace rgbCS = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    if (!isImageMask() && cs instanceof ICC_ColorSpace && !cs.equals(rgbCS)) {
      ColorConvertOp op = new ColorConvertOp(cs, rgbCS, null);

      BufferedImage converted =
          new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);

      bi = op.filter(bi, converted);
    }

    // add in the alpha data supplied by the SMask, if any
    PDFImage sMaskImage = getSMask();
    if (sMaskImage != null) {
      BufferedImage si = sMaskImage.getImage();
      BufferedImage outImage =
          new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);

      int[] srcArray = new int[this.width];
      int[] maskArray = new int[this.width];

      for (int i = 0; i < this.height; i++) {
        bi.getRGB(0, i, this.width, 1, srcArray, 0, this.width);
        si.getRGB(0, i, this.width, 1, maskArray, 0, this.width);

        for (int j = 0; j < this.width; j++) {
          int ac = 0xff000000;

          maskArray[j] = ((maskArray[j] & 0xff) << 24) | (srcArray[j] & ~ac);
        }

        outImage.setRGB(0, i, this.width, 1, maskArray, 0, this.width);
      }

      bi = outImage;
    }

    return (bi);
  }