Esempio n. 1
0
 byte[] getJar(String address) {
   // System.out.println("getJar: "+address);
   byte[] data;
   try {
     URL url = new URL(address);
     IJ.showStatus("Connecting to " + IJ.URL);
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     if (IJ.debugMode) IJ.log("Updater (url): " + address + " " + len);
     if (len <= 0) return null;
     String name = address.contains("wsr") ? "daily build (" : "ij.jar (";
     IJ.showStatus("Downloading " + name + IJ.d2s((double) len / 1048576, 1) + "MB)");
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int n = 0;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) throw new EOFException();
       n += count;
       IJ.showProgress(n, len);
     }
     in.close();
   } catch (IOException e) {
     if (IJ.debugMode) IJ.log("" + e);
     return null;
   }
   if (IJ.debugMode) IJ.wait(6000);
   return data;
 }
Esempio n. 2
0
 short[] readCompressed16bitImage(InputStream in) throws IOException {
   if (IJ.debugMode) IJ.log("ImageReader.read16bit, offset=" + fi.stripOffsets[0]);
   short[] pixels = new short[nPixels];
   int base = 0;
   short last = 0;
   for (int k = 0; k < fi.stripOffsets.length; k++) {
     // IJ.log("seek: "+fi.stripOffsets[k]+" "+fi.stripLengths[k]+"  "+(in instanceof
     // RandomAccessStream));
     if (in instanceof RandomAccessStream) ((RandomAccessStream) in).seek(fi.stripOffsets[k]);
     else if (k > 0) {
       long skip =
           (fi.stripOffsets[k] & 0xffffffffL)
               - (fi.stripOffsets[k - 1] & 0xffffffffL)
               - fi.stripLengths[k - 1];
       if (skip > 0L) in.skip(skip);
     }
     byte[] byteArray = new byte[fi.stripLengths[k]];
     int read = 0, left = byteArray.length;
     while (left > 0) {
       int r = in.read(byteArray, read, left);
       if (r == -1) {
         eofError();
         break;
       }
       read += r;
       left -= r;
     }
     byteArray = uncompress(byteArray);
     int pixelsRead = byteArray.length / bytesPerPixel;
     pixelsRead = pixelsRead - (pixelsRead % fi.width);
     int pmax = base + pixelsRead;
     if (pmax > nPixels) pmax = nPixels;
     if (fi.intelByteOrder) {
       for (int i = base, j = 0; i < pmax; i++, j += 2)
         pixels[i] = (short) (((byteArray[j + 1] & 0xff) << 8) | (byteArray[j] & 0xff));
     } else {
       for (int i = base, j = 0; i < pmax; i++, j += 2)
         pixels[i] = (short) (((byteArray[j] & 0xff) << 8) | (byteArray[j + 1] & 0xff));
     }
     if (fi.compression == FileInfo.LZW_WITH_DIFFERENCING) {
       for (int b = base; b < pmax; b++) {
         pixels[b] += last;
         last = b % fi.width == fi.width - 1 ? 0 : pixels[b];
       }
     }
     base += pixelsRead;
     showProgress(k + 1, fi.stripOffsets.length);
   }
   if (fi.fileType == FileInfo.GRAY16_SIGNED) {
     // convert to unsigned
     for (int i = 0; i < nPixels; i++) pixels[i] = (short) (pixels[i] + 32768);
   }
   return pixels;
 }
Esempio n. 3
0
 /** Reads the pixel data from an image described by a FileInfo object. */
 Object readPixels(FileInfo fi) {
   Object pixels = null;
   try {
     InputStream is = createInputStream(fi);
     if (is == null) return null;
     ImageReader reader = new ImageReader(fi);
     pixels = reader.readPixels(is);
     minValue = reader.min;
     maxValue = reader.max;
     is.close();
   } catch (Exception e) {
     if (!Macro.MACRO_CANCELED.equals(e.getMessage())) IJ.handleException(e);
   }
   return pixels;
 }
Esempio n. 4
0
 String openUrlAsString(String address, int maxLines) {
   StringBuffer sb;
   try {
     URL url = new URL(address);
     InputStream in = url.openStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(in));
     sb = new StringBuffer();
     int count = 0;
     String line;
     while ((line = br.readLine()) != null && count++ < maxLines) sb.append(line + "\n");
     in.close();
   } catch (IOException e) {
     sb = null;
   }
   return sb != null ? new String(sb) : null;
 }
Esempio n. 5
0
 /** Opens a stack of images. */
 ImagePlus openStack(ColorModel cm, boolean show) {
   ImageStack stack = new ImageStack(fi.width, fi.height, cm);
   long skip = fi.getOffset();
   Object pixels;
   try {
     ImageReader reader = new ImageReader(fi);
     InputStream is = createInputStream(fi);
     if (is == null) return null;
     IJ.resetEscape();
     for (int i = 1; i <= fi.nImages; i++) {
       if (!silentMode) IJ.showStatus("Reading: " + i + "/" + fi.nImages);
       if (IJ.escapePressed()) {
         IJ.beep();
         IJ.showProgress(1.0);
         silentMode = false;
         return null;
       }
       pixels = reader.readPixels(is, skip);
       if (pixels == null) break;
       stack.addSlice(null, pixels);
       skip = fi.gapBetweenImages;
       if (!silentMode) IJ.showProgress(i, fi.nImages);
     }
     is.close();
   } catch (Exception e) {
     IJ.log("" + e);
   } catch (OutOfMemoryError e) {
     IJ.outOfMemory(fi.fileName);
     stack.trim();
   }
   if (!silentMode) IJ.showProgress(1.0);
   if (stack.getSize() == 0) return null;
   if (fi.sliceLabels != null && fi.sliceLabels.length <= stack.getSize()) {
     for (int i = 0; i < fi.sliceLabels.length; i++) stack.setSliceLabel(fi.sliceLabels[i], i + 1);
   }
   ImagePlus imp = new ImagePlus(fi.fileName, stack);
   if (fi.info != null) imp.setProperty("Info", fi.info);
   if (show) imp.show();
   imp.setFileInfo(fi);
   setCalibration(imp);
   ImageProcessor ip = imp.getProcessor();
   if (ip.getMin() == ip.getMax()) // find stack min and max if first slice is blank
   setStackDisplayRange(imp);
   if (!silentMode) IJ.showProgress(1.0);
   silentMode = false;
   return imp;
 }
 public static byte[] download(String urlString, String name) {
   int maxLength = 52428800; // 50MB
   URL url = null;
   boolean unknownLength = false;
   byte[] data = null;
   ;
   int n = 0;
   try {
     url = new URL(urlString);
     if (IJ.debugMode) IJ.log("PluginInstaller: " + urlString + "  " + url);
     if (url == null) return null;
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     unknownLength = len < 0;
     if (unknownLength) len = maxLength;
     if (name != null) IJ.showStatus("Downloading " + url.getFile());
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int lenk = len / 1024;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) break;
       n += count;
       if (name != null)
         IJ.showStatus("Downloading " + name + " (" + (n / 1024) + "/" + lenk + "k)");
       IJ.showProgress(n, len);
     }
     in.close();
   } catch (Exception e) {
     String msg = "" + e;
     if (!msg.contains("://")) msg += "\n   " + urlString;
     IJ.error("Plugin Installer", msg);
     return null;
   } finally {
     IJ.showProgress(1.0);
   }
   if (name != null) IJ.showStatus("");
   if (unknownLength) {
     byte[] data2 = data;
     data = new byte[n];
     for (int i = 0; i < n; i++) data[i] = data2[i];
   }
   return data;
 }
Esempio n. 7
0
  float[] read64bitImage(InputStream in) throws IOException {
    int pixelsRead;
    byte[] buffer = new byte[bufferSize];
    float[] pixels = new float[nPixels];
    long totalRead = 0L;
    int base = 0;
    int count, value;
    int bufferCount;
    long tmp;
    long b1, b2, b3, b4, b5, b6, b7, b8;

    while (totalRead < byteCount) {
      if ((totalRead + bufferSize) > byteCount) bufferSize = (int) (byteCount - totalRead);
      bufferCount = 0;
      while (bufferCount < bufferSize) { // fill the buffer
        count = in.read(buffer, bufferCount, bufferSize - bufferCount);
        if (count == -1) {
          if (bufferCount > 0) for (int i = bufferCount; i < bufferSize; i++) buffer[i] = 0;
          totalRead = byteCount;
          eofError();
          break;
        }
        bufferCount += count;
      }
      totalRead += bufferSize;
      showProgress(totalRead, byteCount);
      pixelsRead = bufferSize / bytesPerPixel;
      int j = 0;
      for (int i = base; i < (base + pixelsRead); i++) {
        b1 = buffer[j + 7] & 0xff;
        b2 = buffer[j + 6] & 0xff;
        b3 = buffer[j + 5] & 0xff;
        b4 = buffer[j + 4] & 0xff;
        b5 = buffer[j + 3] & 0xff;
        b6 = buffer[j + 2] & 0xff;
        b7 = buffer[j + 1] & 0xff;
        b8 = buffer[j] & 0xff;
        if (fi.intelByteOrder)
          tmp =
              (long)
                  ((b1 << 56) | (b2 << 48) | (b3 << 40) | (b4 << 32) | (b5 << 24) | (b6 << 16)
                      | (b7 << 8) | b8);
        else
          tmp =
              (long)
                  ((b8 << 56) | (b7 << 48) | (b6 << 40) | (b5 << 32) | (b4 << 24) | (b3 << 16)
                      | (b2 << 8) | b1);
        pixels[i] = (float) Double.longBitsToDouble(tmp);
        j += 8;
      }
      base += pixelsRead;
    }
    return pixels;
  }
Esempio n. 8
0
 byte[] readCompressed8bitImage(InputStream in) throws IOException {
   byte[] pixels = new byte[nPixels];
   int current = 0;
   byte last = 0;
   for (int i = 0; i < fi.stripOffsets.length; i++) {
     if (in instanceof RandomAccessStream) ((RandomAccessStream) in).seek(fi.stripOffsets[i]);
     else if (i > 0) {
       long skip =
           (fi.stripOffsets[i] & 0xffffffffL)
               - (fi.stripOffsets[i - 1] & 0xffffffffL)
               - fi.stripLengths[i - 1];
       if (skip > 0L) in.skip(skip);
     }
     byte[] byteArray = new byte[fi.stripLengths[i]];
     int read = 0, left = byteArray.length;
     while (left > 0) {
       int r = in.read(byteArray, read, left);
       if (r == -1) {
         eofError();
         break;
       }
       read += r;
       left -= r;
     }
     byteArray = uncompress(byteArray);
     int length = byteArray.length;
     length = length - (length % fi.width);
     if (fi.compression == FileInfo.LZW_WITH_DIFFERENCING) {
       for (int b = 0; b < length; b++) {
         byteArray[b] += last;
         last = b % fi.width == fi.width - 1 ? 0 : byteArray[b];
       }
     }
     if (current + length > pixels.length) length = pixels.length - current;
     System.arraycopy(byteArray, 0, pixels, current, length);
     current += length;
     showProgress(i + 1, fi.stripOffsets.length);
   }
   return pixels;
 }
Esempio n. 9
0
 public Properties decodeDescriptionString(FileInfo fi) {
   if (fi.description == null || fi.description.length() < 7) return null;
   if (IJ.debugMode) IJ.log("Image Description: " + new String(fi.description).replace('\n', ' '));
   if (!fi.description.startsWith("ImageJ")) return null;
   Properties props = new Properties();
   InputStream is = new ByteArrayInputStream(fi.description.getBytes());
   try {
     props.load(is);
     is.close();
   } catch (IOException e) {
     return null;
   }
   fi.unit = props.getProperty("unit", "");
   Double n = getNumber(props, "cf");
   if (n != null) fi.calibrationFunction = n.intValue();
   double c[] = new double[5];
   int count = 0;
   for (int i = 0; i < 5; i++) {
     n = getNumber(props, "c" + i);
     if (n == null) break;
     c[i] = n.doubleValue();
     count++;
   }
   if (count >= 2) {
     fi.coefficients = new double[count];
     for (int i = 0; i < count; i++) fi.coefficients[i] = c[i];
   }
   fi.valueUnit = props.getProperty("vunit");
   n = getNumber(props, "images");
   if (n != null && n.doubleValue() > 1.0) fi.nImages = (int) n.doubleValue();
   if (fi.nImages > 1) {
     double spacing = getDouble(props, "spacing");
     if (spacing != 0.0) {
       if (spacing < 0) spacing = -spacing;
       fi.pixelDepth = spacing;
     }
   }
   return props;
 }
Esempio n. 10
0
 byte[] getJar(String address) {
   byte[] data;
   boolean gte133 = version().compareTo("1.33u") >= 0;
   try {
     URL url = new URL(address);
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     String name = address.endsWith("ij/ij.jar") ? "daily build" : "ij.jar";
     IJ.showStatus("Downloading ij.jar (" + IJ.d2s((double) len / 1048576, 1) + "MB)");
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int n = 0;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) throw new EOFException();
       n += count;
       if (gte133) IJ.showProgress(n, len);
     }
     in.close();
   } catch (IOException e) {
     return null;
   }
   return data;
 }
Esempio n. 11
0
  /** Reads a 16-bit image. Signed pixels are converted to unsigned by adding 32768. */
  short[] read16bitImage(InputStream in) throws IOException {
    if (fi.compression > FileInfo.COMPRESSION_NONE
        || (fi.stripOffsets != null && fi.stripOffsets.length > 1)
            && fi.fileType != FileInfo.RGB48_PLANAR) return readCompressed16bitImage(in);
    int pixelsRead;
    byte[] buffer = new byte[bufferSize];
    short[] pixels = new short[nPixels];
    long totalRead = 0L;
    int base = 0;
    int count, value;
    int bufferCount;

    while (totalRead < byteCount) {
      if ((totalRead + bufferSize) > byteCount) bufferSize = (int) (byteCount - totalRead);
      bufferCount = 0;
      while (bufferCount < bufferSize) { // fill the buffer
        count = in.read(buffer, bufferCount, bufferSize - bufferCount);
        if (count == -1) {
          if (bufferCount > 0) for (int i = bufferCount; i < bufferSize; i++) buffer[i] = 0;
          totalRead = byteCount;
          eofError();
          break;
        }
        bufferCount += count;
      }
      totalRead += bufferSize;
      showProgress(totalRead, byteCount);
      pixelsRead = bufferSize / bytesPerPixel;
      if (fi.intelByteOrder) {
        if (fi.fileType == FileInfo.GRAY16_SIGNED)
          for (int i = base, j = 0; i < (base + pixelsRead); i++, j += 2)
            pixels[i] = (short) ((((buffer[j + 1] & 0xff) << 8) | (buffer[j] & 0xff)) + 32768);
        else
          for (int i = base, j = 0; i < (base + pixelsRead); i++, j += 2)
            pixels[i] = (short) (((buffer[j + 1] & 0xff) << 8) | (buffer[j] & 0xff));
      } else {
        if (fi.fileType == FileInfo.GRAY16_SIGNED)
          for (int i = base, j = 0; i < (base + pixelsRead); i++, j += 2)
            pixels[i] = (short) ((((buffer[j] & 0xff) << 8) | (buffer[j + 1] & 0xff)) + 32768);
        else
          for (int i = base, j = 0; i < (base + pixelsRead); i++, j += 2)
            pixels[i] = (short) (((buffer[j] & 0xff) << 8) | (buffer[j + 1] & 0xff));
      }
      base += pixelsRead;
    }
    return pixels;
  }
Esempio n. 12
0
 byte[] read8bitImage(InputStream in) throws IOException {
   if (fi.compression > FileInfo.COMPRESSION_NONE) return readCompressed8bitImage(in);
   byte[] pixels = new byte[nPixels];
   // assume contiguous strips
   int count, actuallyRead;
   int totalRead = 0;
   while (totalRead < byteCount) {
     if (totalRead + bufferSize > byteCount) count = (int) (byteCount - totalRead);
     else count = bufferSize;
     actuallyRead = in.read(pixels, totalRead, count);
     if (actuallyRead == -1) {
       eofError();
       break;
     }
     totalRead += actuallyRead;
     showProgress(totalRead, byteCount);
   }
   return pixels;
 }
Esempio n. 13
0
 void skip(InputStream in) throws IOException {
   if (skipCount > 0) {
     long bytesRead = 0;
     int skipAttempts = 0;
     long count;
     while (bytesRead < skipCount) {
       count = in.skip(skipCount - bytesRead);
       skipAttempts++;
       if (count == -1 || skipAttempts > 5) break;
       bytesRead += count;
       // IJ.log("skip: "+skipCount+" "+count+" "+bytesRead+" "+skipAttempts);
     }
   }
   byteCount = ((long) width) * height * bytesPerPixel;
   if (fi.fileType == FileInfo.BITMAP) {
     int scan = width / 8, pad = width % 8;
     if (pad > 0) scan++;
     byteCount = scan * height;
   }
   nPixels = width * height;
   bufferSize = (int) (byteCount / 25L);
   if (bufferSize < 8192) bufferSize = 8192;
   else bufferSize = (bufferSize / 8192) * 8192;
 }
Esempio n. 14
0
  float[] read32bitImage(InputStream in) throws IOException {
    if (fi.compression > FileInfo.COMPRESSION_NONE
        || (fi.stripOffsets != null && fi.stripOffsets.length > 1))
      return readCompressed32bitImage(in);
    int pixelsRead;
    byte[] buffer = new byte[bufferSize];
    float[] pixels = new float[nPixels];
    long totalRead = 0L;
    int base = 0;
    int count, value;
    int bufferCount;
    int tmp;

    while (totalRead < byteCount) {
      if ((totalRead + bufferSize) > byteCount) bufferSize = (int) (byteCount - totalRead);
      bufferCount = 0;
      while (bufferCount < bufferSize) { // fill the buffer
        count = in.read(buffer, bufferCount, bufferSize - bufferCount);
        if (count == -1) {
          if (bufferCount > 0) for (int i = bufferCount; i < bufferSize; i++) buffer[i] = 0;
          totalRead = byteCount;
          eofError();
          break;
        }
        bufferCount += count;
      }
      totalRead += bufferSize;
      showProgress(totalRead, byteCount);
      pixelsRead = bufferSize / bytesPerPixel;
      int pmax = base + pixelsRead;
      if (pmax > nPixels) pmax = nPixels;
      int j = 0;
      if (fi.intelByteOrder)
        for (int i = base; i < pmax; i++) {
          tmp =
              (int)
                  (((buffer[j + 3] & 0xff) << 24)
                      | ((buffer[j + 2] & 0xff) << 16)
                      | ((buffer[j + 1] & 0xff) << 8)
                      | (buffer[j] & 0xff));
          if (fi.fileType == FileInfo.GRAY32_FLOAT) pixels[i] = Float.intBitsToFloat(tmp);
          else if (fi.fileType == FileInfo.GRAY32_UNSIGNED) pixels[i] = (float) (tmp & 0xffffffffL);
          else pixels[i] = tmp;
          j += 4;
        }
      else
        for (int i = base; i < pmax; i++) {
          tmp =
              (int)
                  (((buffer[j] & 0xff) << 24)
                      | ((buffer[j + 1] & 0xff) << 16)
                      | ((buffer[j + 2] & 0xff) << 8)
                      | (buffer[j + 3] & 0xff));
          if (fi.fileType == FileInfo.GRAY32_FLOAT) pixels[i] = Float.intBitsToFloat(tmp);
          else if (fi.fileType == FileInfo.GRAY32_UNSIGNED) pixels[i] = (float) (tmp & 0xffffffffL);
          else pixels[i] = tmp;
          j += 4;
        }
      base += pixelsRead;
    }
    return pixels;
  }
Esempio n. 15
0
 float[] readCompressed32bitImage(InputStream in) throws IOException {
   float[] pixels = new float[nPixels];
   int base = 0;
   float last = 0;
   for (int k = 0; k < fi.stripOffsets.length; k++) {
     // IJ.log("seek: "+fi.stripOffsets[k]+" "+(in instanceof RandomAccessStream));
     if (in instanceof RandomAccessStream) ((RandomAccessStream) in).seek(fi.stripOffsets[k]);
     else if (k > 0) {
       long skip =
           (fi.stripOffsets[k] & 0xffffffffL)
               - (fi.stripOffsets[k - 1] & 0xffffffffL)
               - fi.stripLengths[k - 1];
       if (skip > 0L) in.skip(skip);
     }
     byte[] byteArray = new byte[fi.stripLengths[k]];
     int read = 0, left = byteArray.length;
     while (left > 0) {
       int r = in.read(byteArray, read, left);
       if (r == -1) {
         eofError();
         break;
       }
       read += r;
       left -= r;
     }
     byteArray = uncompress(byteArray);
     int pixelsRead = byteArray.length / bytesPerPixel;
     pixelsRead = pixelsRead - (pixelsRead % fi.width);
     int pmax = base + pixelsRead;
     if (pmax > nPixels) pmax = nPixels;
     int tmp;
     if (fi.intelByteOrder) {
       for (int i = base, j = 0; i < pmax; i++, j += 4) {
         tmp =
             (int)
                 (((byteArray[j + 3] & 0xff) << 24)
                     | ((byteArray[j + 2] & 0xff) << 16)
                     | ((byteArray[j + 1] & 0xff) << 8)
                     | (byteArray[j] & 0xff));
         if (fi.fileType == FileInfo.GRAY32_FLOAT) pixels[i] = Float.intBitsToFloat(tmp);
         else if (fi.fileType == FileInfo.GRAY32_UNSIGNED) pixels[i] = (float) (tmp & 0xffffffffL);
         else pixels[i] = tmp;
       }
     } else {
       for (int i = base, j = 0; i < pmax; i++, j += 4) {
         tmp =
             (int)
                 (((byteArray[j] & 0xff) << 24)
                     | ((byteArray[j + 1] & 0xff) << 16)
                     | ((byteArray[j + 2] & 0xff) << 8)
                     | (byteArray[j + 3] & 0xff));
         if (fi.fileType == FileInfo.GRAY32_FLOAT) pixels[i] = Float.intBitsToFloat(tmp);
         else if (fi.fileType == FileInfo.GRAY32_UNSIGNED) pixels[i] = (float) (tmp & 0xffffffffL);
         else pixels[i] = tmp;
       }
     }
     if (fi.compression == FileInfo.LZW_WITH_DIFFERENCING) {
       for (int b = base; b < pmax; b++) {
         pixels[b] += last;
         last = b % fi.width == fi.width - 1 ? 0 : pixels[b];
       }
     }
     base += pixelsRead;
     showProgress(k + 1, fi.stripOffsets.length);
   }
   return pixels;
 }
Esempio n. 16
0
  int[] readChunkyRGB(InputStream in) throws IOException {
    if (fi.compression == FileInfo.JPEG) return readJPEG(in);
    else if (fi.compression > FileInfo.COMPRESSION_NONE
        || (fi.stripOffsets != null && fi.stripOffsets.length > 1))
      return readCompressedChunkyRGB(in);
    int pixelsRead;
    bufferSize = 24 * width;
    byte[] buffer = new byte[bufferSize];
    int[] pixels = new int[nPixels];
    long totalRead = 0L;
    int base = 0;
    int count, value;
    int bufferCount;
    int r, g, b, a;

    while (totalRead < byteCount) {
      if ((totalRead + bufferSize) > byteCount) bufferSize = (int) (byteCount - totalRead);
      bufferCount = 0;
      while (bufferCount < bufferSize) { // fill the buffer
        count = in.read(buffer, bufferCount, bufferSize - bufferCount);
        if (count == -1) {
          if (bufferCount > 0) for (int i = bufferCount; i < bufferSize; i++) buffer[i] = 0;
          totalRead = byteCount;
          eofError();
          break;
        }
        bufferCount += count;
      }
      totalRead += bufferSize;
      showProgress(totalRead, byteCount);
      pixelsRead = bufferSize / bytesPerPixel;
      boolean bgr = fi.fileType == FileInfo.BGR;
      int j = 0;
      for (int i = base; i < (base + pixelsRead); i++) {
        if (bytesPerPixel == 4) {
          if (fi.fileType == FileInfo.BARG) { // MCID
            b = buffer[j++] & 0xff;
            j++; // ignore alfa byte
            r = buffer[j++] & 0xff;
            g = buffer[j++] & 0xff;
          } else if (fi.fileType == FileInfo.ABGR) {
            b = buffer[j++] & 0xff;
            g = buffer[j++] & 0xff;
            r = buffer[j++] & 0xff;
            j++; // ignore alfa byte
          } else if (fi.fileType == FileInfo.CMYK) {
            r = buffer[j++] & 0xff; // c
            g = buffer[j++] & 0xff; // m
            b = buffer[j++] & 0xff; // y
            a = buffer[j++] & 0xff; // k
            if (a > 0) { // if k>0 then  c=c*(1-k)+k
              r = ((r * (256 - a)) >> 8) + a;
              g = ((g * (256 - a)) >> 8) + a;
              b = ((b * (256 - a)) >> 8) + a;
            } // else  r=1-c, g=1-m and b=1-y, which IJ does by inverting image
          } else { // ARGB
            r = buffer[j++] & 0xff;
            g = buffer[j++] & 0xff;
            b = buffer[j++] & 0xff;
            j++; // ignore alfa byte
          }
        } else {
          r = buffer[j++] & 0xff;
          g = buffer[j++] & 0xff;
          b = buffer[j++] & 0xff;
        }
        if (bgr) pixels[i] = 0xff000000 | (b << 16) | (g << 8) | r;
        else pixels[i] = 0xff000000 | (r << 16) | (g << 8) | b;
      }
      base += pixelsRead;
    }
    return pixels;
  }
Esempio n. 17
0
 int[] readCompressedChunkyRGB(InputStream in) throws IOException {
   int[] pixels = new int[nPixels];
   int base = 0;
   int lastRed = 0, lastGreen = 0, lastBlue = 0;
   int nextByte;
   int red = 0, green = 0, blue = 0, alpha = 0;
   boolean bgr = fi.fileType == FileInfo.BGR;
   boolean cmyk = fi.fileType == FileInfo.CMYK;
   boolean differencing = fi.compression == FileInfo.LZW_WITH_DIFFERENCING;
   for (int i = 0; i < fi.stripOffsets.length; i++) {
     if (in instanceof RandomAccessStream) ((RandomAccessStream) in).seek(fi.stripOffsets[i]);
     else if (i > 0) {
       long skip =
           (fi.stripOffsets[i] & 0xffffffffL)
               - (fi.stripOffsets[i - 1] & 0xffffffffL)
               - fi.stripLengths[i - 1];
       if (skip > 0L) in.skip(skip);
     }
     byte[] byteArray = new byte[fi.stripLengths[i]];
     int read = 0, left = byteArray.length;
     while (left > 0) {
       int r = in.read(byteArray, read, left);
       if (r == -1) {
         eofError();
         break;
       }
       read += r;
       left -= r;
     }
     byteArray = uncompress(byteArray);
     if (differencing) {
       for (int b = 0; b < byteArray.length; b++) {
         if (b / bytesPerPixel % fi.width == 0) continue;
         byteArray[b] += byteArray[b - bytesPerPixel];
       }
     }
     int k = 0;
     int pixelsRead = byteArray.length / bytesPerPixel;
     pixelsRead = pixelsRead - (pixelsRead % fi.width);
     int pmax = base + pixelsRead;
     if (pmax > nPixels) pmax = nPixels;
     for (int j = base; j < pmax; j++) {
       if (bytesPerPixel == 4) {
         red = byteArray[k++] & 0xff;
         green = byteArray[k++] & 0xff;
         blue = byteArray[k++] & 0xff;
         alpha = byteArray[k++] & 0xff;
         if (cmyk && alpha > 0) {
           red = ((red * (256 - alpha)) >> 8) + alpha;
           green = ((green * (256 - alpha)) >> 8) + alpha;
           blue = ((blue * (256 - alpha)) >> 8) + alpha;
         }
       } else {
         red = byteArray[k++] & 0xff;
         green = byteArray[k++] & 0xff;
         blue = byteArray[k++] & 0xff;
       }
       if (bgr) pixels[j] = 0xff000000 | (blue << 16) | (green << 8) | red;
       else pixels[j] = 0xff000000 | (red << 16) | (green << 8) | blue;
     }
     base += pixelsRead;
     showProgress(i + 1, fi.stripOffsets.length);
   }
   return pixels;
 }
Esempio n. 18
0
  public void run(String arg) {
    GenericDialog gd = new GenericDialog("Options");
    double sfreq = 20000.0;
    gd.addNumericField("Sampling Frequency?", sfreq, 1, 10, null);
    String[] psfchoice = {"3D Gaussian", "Gaus-Lorentz^2", "2D Gaussian"};
    gd.addChoice("PSF Type?", psfchoice, psfchoice[0]);
    String[] filetypechoice = {
      "Confocor 3 raw", "Short binary trajectory", "PlotWindow trajectory", "Ascii Text File"
    };
    gd.addChoice("File Type?", filetypechoice, filetypechoice[0]);
    boolean ch2green = true;
    gd.addCheckbox("Ch2 is green?", ch2green);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    sfreq = gd.getNextNumber();
    int psfflag = gd.getNextChoiceIndex();
    int fileflag = gd.getNextChoiceIndex();
    ch2green = gd.getNextBoolean();
    int nfiles = 0;
    Object[] histograms = null;
    int xmax = 0;
    int ymax = 0;
    String[] names = null;
    if (fileflag < 2) {
      jdataio ioclass = new jdataio();
      File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
      if (filearray.length == 0) {
        return;
      }
      String dir = filearray[0].getAbsolutePath();
      int sepindex = dir.lastIndexOf(File.separator);
      String newdir = dir.substring(0, sepindex + 1);
      OpenDialog.setDefaultDirectory(newdir);
      nfiles = filearray.length / 2;
      if (nfiles > 25) {
        nfiles = 25;
      }
      histograms = new Object[nfiles];
      names = organize_c3_files(filearray);
      for (int i = 0; i < nfiles; i++) {
        try {
          int length1 = (int) (((double) filearray[2 * i].length() - 128.0) / 4.0);
          int length2 = (int) (((double) filearray[2 * i + 1].length() - 128.0) / 4.0);
          int length3 = (int) (((double) filearray[2 * i].length()) / 2.0);
          int length4 = (int) (((double) filearray[2 * i + 1].length()) / 2.0);
          InputStream instream = new BufferedInputStream(new FileInputStream(filearray[2 * i]));
          InputStream instream2 =
              new BufferedInputStream(new FileInputStream(filearray[2 * i + 1]));
          if (fileflag == 0) {
            int[] pmdata = new int[length1];
            int[] pmdata2 = new int[length2];
            if (!ioclass.skipstreambytes(instream, 128)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.skipstreambytes(instream2, 128)) {
              showioerror();
              instream2.close();
              return;
            }
            if (!ioclass.readintelintfile(instream, length1, pmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelintfile(instream2, length2, pmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata2, pmdata, sfreq, 20000000);
            } else {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata, pmdata2, sfreq, 20000000);
            }
          } else {
            float[] tmdata = new float[length3];
            float[] tmdata2 = new float[length4];
            if (!ioclass.readintelshortfile(instream, length3, tmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelshortfile(instream2, length4, tmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata2, tmdata);
            } else {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata, tmdata2);
            }
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
          instream.close();
          instream2.close();
        } catch (IOException e) {
          showioerror();
          return;
        }
      }
    } else {
      if (fileflag == 2) {
        ImageWindow iw = WindowManager.getCurrentWindow();
        float[][] trajectories = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues");
        float[][] tempxvals = (float[][]) jutils.runPW4VoidMethod(iw, "getXValues");
        sfreq = 1.0 / ((double) tempxvals[0][1]);
        nfiles = trajectories.length / 2;
        if (nfiles > 25) {
          nfiles = 25;
        }
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        histograms = new Object[nfiles];
        for (int i = 0; i < nfiles; i++) {
          names[i] = "trajectory " + (i + 1);
          if (ch2green) {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i + 1], trajectories[2 * i]);
          } else {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i], trajectories[2 * i + 1]);
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      } else {
        // here we read tab delimited lines from files
        jdataio ioclass = new jdataio();
        File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
        if (filearray.length == 0) {
          return;
        }
        String dir = filearray[0].getAbsolutePath();
        int sepindex = dir.lastIndexOf(File.separator);
        String newdir = dir.substring(0, sepindex + 1);
        OpenDialog.setDefaultDirectory(newdir);
        nfiles = filearray.length;
        if (nfiles > 25) {
          nfiles = 25;
        }
        histograms = new Object[nfiles];
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        for (int i = 0; i < nfiles; i++) {
          try {
            names[i] = filearray[i].getName();
            BufferedReader d = new BufferedReader(new FileReader(filearray[i]));
            String[] lines = new String[256];
            int counter = 0;
            do {
              lines[counter] = d.readLine();
              counter++;
            } while ((lines[counter - 1] != null && lines[counter - 1] != "") && counter < 256);
            int numcolumns = 0;
            for (int j = 0; j < counter - 1; j++) {
              int temp = getncolumns(lines[j]);
              if (temp > numcolumns) {
                numcolumns = temp;
              }
            }
            float[][] temphist2 = null;
            if (ch2green) {
              temphist2 = new float[numcolumns][counter - 1];
            } else {
              temphist2 = new float[counter - 1][numcolumns];
            }
            for (int k = 0; k < counter - 1; k++) {
              float[] temp = tab_delim2float(lines[k]);
              for (int j = 0; j < numcolumns; j++) {
                if (ch2green) {
                  temphist2[j][k] = temp[j];
                } else {
                  temphist2[k][j] = temp[j];
                }
              }
            }
            histograms[i] = temphist2;
            d.close();
          } catch (IOException e) {
            showioerror();
            return;
          }
        }
        for (int i = 0; i < nfiles; i++) {
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      }
    }
    // note that here x is green and y is red
    float[][][] pch = new float[nfiles][xmax][ymax];
    for (int i = 0; i < nfiles; i++) {
      for (int j = 0; j < ((float[][]) histograms[i]).length; j++) {
        for (int k = 0; k < ((float[][]) histograms[i])[j].length; k++) {
          pch[i][j][k] = ((float[][]) histograms[i])[j][k];
        }
      }
    }

    final PCH2DFitWindow cw = new PCH2DFitWindow();
    cw.init(names, pch, psfflag);

    final Frame f = new Frame("PCH 2D Analysis");
    f.setLocation(10, 10);
    f.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            f.dispose();
          }
        });

    f.add(cw);
    f.pack();
    f.setResizable(false);
    Insets ins = f.getInsets();
    cw.totalSize.height = PCH2DFitWindow.H + ins.bottom + ins.top + 65;
    cw.totalSize.width = PCH2DFitWindow.WR + ins.left + ins.right;
    f.setSize(cw.totalSize);
    f.setVisible(true);
    cw.requestFocus();
  }
Esempio n. 19
0
  private Object tryOpen(String directory, String name, String path) {
    // set up a stream to read in 132 bytes from the file header
    // These can be checked for "magic" values which are diagnostic
    // of some image types
    InputStream is;
    byte[] buf = new byte[132];
    try {
      if (0 == path.indexOf("http://")) is = new java.net.URL(path).openStream();
      else is = new FileInputStream(path);
      is.read(buf, 0, 132);
      is.close();
    } catch (IOException e) {
      // couldn't open the file for reading
      return null;
    }
    name = name.toLowerCase();
    width = PLUGIN_NOT_FOUND;

    // Temporarily suppress "plugin not found" errors if LOCI Bio-Formats plugin is installed
    if (Menus.getCommands().get("Bio-Formats Importer") != null
        && IJ.getVersion().compareTo("1.37u") >= 0) IJ.suppressPluginNotFoundError();

    // OK now we get to the interesting bit

    // GJ: added Biorad PIC confocal file handler
    // ------------------------------------------
    // These make 12345 if you read them as the right kind of short
    // and should have this value in every Biorad PIC file
    if (buf[54] == 57 && buf[55] == 48) {
      return tryPlugIn("Biorad_Reader", path);
    }
    // GJ: added Gatan Digital Micrograph DM3 handler
    // ----------------------------------------------
    // check if the file ends in .DM3 or .dm3,
    // and bytes make an int value of 3 which is the DM3 version number
    if (name.endsWith(".dm3") && buf[0] == 0 && buf[1] == 0 && buf[2] == 0 && buf[3] == 3) {
      return tryPlugIn("DM3_Reader", path);
    }

    // IPLab file handler
    // Little-endian IPLab files start with "iiii" or "mmmm".
    if (name.endsWith(".ipl")
        || (buf[0] == 105 && buf[1] == 105 && buf[2] == 105 && buf[3] == 105)
        || (buf[0] == 109 && buf[1] == 109 && buf[2] == 109 && buf[3] == 109)) {
      return tryPlugIn("IPLab_Reader", path);
    }

    // Packard InstantImager format (.img) handler -> check HERE
    // before Analyze check below!
    // Check extension and signature bytes KAJ_
    if (name.endsWith(".img") && buf[0] == 75 && buf[1] == 65 && buf[2] == 74 && buf[3] == 0) {
      return tryPlugIn("InstantImager_Reader", path);
    }

    // Analyze format (.img/.hdr) handler
    // Opens the file using the Nifti_Reader if it is installed,
    // otherwise the Analyze_Reader is used. Note that
    // the Analyze_Reader plugin opens and displays the
    // image and does not implement the ImagePlus class.
    if (name.endsWith(".img") || name.endsWith(".hdr")) {
      if (Menus.getCommands().get("NIfTI-Analyze") != null) return tryPlugIn("Nifti_Reader", path);
      else return tryPlugIn("Analyze_Reader", path);
    }

    // NIFTI format (.nii) handler
    if (name.endsWith(".nii") || name.endsWith(".nii.gz") || name.endsWith(".nii.z")) {
      return tryPlugIn("Nifti_Reader", path);
    }

    // Image Cytometry Standard (.ics) handler
    // http://valelab.ucsf.edu/~nico/IJplugins/Ics_Opener.html
    if (name.endsWith(".ics")) {
      return tryPlugIn("Ics_Opener", path);
    }

    // Princeton Instruments SPE image file (.spe) handler
    // http://rsb.info.nih.gov/ij/plugins/spe.html
    if (name.endsWith(".spe")) {
      return tryPlugIn("OpenSPE_", path);
    }

    // Zeiss Confocal LSM 510 image file (.lsm) handler
    // http://rsb.info.nih.gov/ij/plugins/lsm-reader.html
    if (name.endsWith(".lsm")) {
      Object obj = tryPlugIn("LSM_Reader", path);
      if (obj == null && Menus.getCommands().get("Show LSMToolbox") != null)
        obj = tryPlugIn("LSM_Toolbox", "file=" + path);
      return obj;
    }

    // BM: added Bruker file handler 29.07.04
    if (name.equals("ser")
        || name.equals("fid")
        || name.equals("2rr")
        || name.equals("2ii")
        || name.equals("3rrr")
        || name.equals("3iii")
        || name.equals("2dseq")) {
      ij.IJ.showStatus("Opening Bruker " + name + " File");
      return tryPlugIn("BrukerOpener", name + "|" + path);
    }

    // AVI: open AVI files using AVI_Reader plugin
    if (name.endsWith(".avi")) {
      return tryPlugIn("AVI_Reader", path);
    }

    // QuickTime: open .mov and .pict files using QT_Movie_Opener plugin
    if (name.endsWith(".mov") || name.endsWith(".pict")) {
      return tryPlugIn("QT_Movie_Opener", path);
    }

    // ZVI file handler
    // Little-endian ZVI and Thumbs.db files start with d0 cf 11 e0
    // so we can only look at the extension.
    if (name.endsWith(".zvi")) {
      return tryPlugIn("ZVI_Reader", path);
    }

    // University of North Carolina (UNC) file format handler
    // 'magic' numbers are (int) offsets to data structures and
    // may change in future releases.
    if (name.endsWith(".unc")
        || (buf[3] == 117 && buf[7] == -127 && buf[11] == 36 && buf[14] == 32 && buf[15] == -127)) {
      return tryPlugIn("UNC_Reader", path);
    }

    // Amira file handler
    // http://wbgn013.biozentrum.uni-wuerzburg.de/ImageJ/amira-io.html
    if (buf[0] == 0x23
        && buf[1] == 0x20
        && buf[2] == 0x41
        && buf[3] == 0x6d
        && buf[4] == 0x69
        && buf[5] == 0x72
        && buf[6] == 0x61
        && buf[7] == 0x4d
        && buf[8] == 0x65
        && buf[9] == 0x73
        && buf[10] == 0x68
        && buf[11] == 0x20) {
      return tryPlugIn("AmiraMeshReader_", path);
    }

    // Deltavision file handler
    // Open DV files generated on Applied Precision DeltaVision systems
    if (name.endsWith(".dv") || name.endsWith(".r3d")) {
      return tryPlugIn("Deltavision_Opener", path);
    }

    // Albert Cardona: read .mrc files (little endian).
    // Documentation at: http://ami.scripps.edu/prtl_data/mrc_specification.htm.
    // The parsing of the header is a bare minimum of what could be done.
    if (name.endsWith(".mrc")) {
      return tryPlugIn("Open_MRC_Leginon", path);
    }

    // Albert Cardona: read .dat files from the EMMENU software
    if (name.endsWith(".dat") && 1 == buf[1] && 0 == buf[2]) { // 'new format' only
      return tryPlugIn("Open_DAT_EMMENU", path);
    }

    // Timo Rantalainen and Michael Doube: read Stratec pQCT files.
    // File name is IDDDDDDD.MHH, where D is decimal and H is hex.
    if (name.matches("[iI]\\d{7}\\.[mM]\\p{XDigit}{2}")) {
      return tryPlugIn("org.doube.bonej.pqct.Read_Stratec_File", path);
    }

    // Michael Doube: read Scanco ISQ files
    // File name is ADDDDDDD.ISQ;D where D is a decimal and A is a letter
    try {
      String isqMagic = new String(buf, 0, 16, "UTF-8");
      if (name.matches("[a-z]\\d{7}.isq;\\d+") || isqMagic.equals("CTDATA-HEADER_V1"))
        return tryPlugIn("org.bonej.io.ISQReader", path);
    } catch (Exception e) {
    }

    // David Mills: read Queen Mary MCD files
    if (name.endsWith(".mcd")) {
      return tryPlugIn("mcdReader", path);
    }
    // David Mills: read Queen Mary TOM files
    if (name.endsWith(".tom")) {
      return tryPlugIn("tomReader", path);
    }

    // ****************** MODIFY HERE ******************
    // do what ever you have to do to recognise your own file type
    // and then call appropriate plugin using the above as models
    // e.g.:

    /*
    // A. Dent: Added XYZ handler
    // ----------------------------------------------
    // check if the file ends in .xyz, and bytes 0 and 1 equal 42
    if (name.endsWith(".xyz") && buf[0]==42 && buf[1]==42) {
    // Ok we've identified the file type - now load it
    	return tryPlugIn("XYZ_Reader", path);
    }
    */

    return null;
  }