Esempio n. 1
0
  /**
   * Creates an immutable image using pixel data from the specified region of a source image,
   * transformed as specified.
   *
   * <p>The source image may be mutable or immutable. For immutable source images, transparency
   * information, if any, is copied to the new image unchanged.
   *
   * <p>On some devices, pre-transformed images may render more quickly than images that are
   * transformed on the fly using <code>drawRegion</code>. However, creating such images does
   * consume additional heap space, so this technique should be applied only to images whose
   * rendering speed is critical.
   *
   * <p>The transform function used must be one of the following, as defined in the {@link
   * javax.microedition.lcdui.game.Sprite Sprite} class:<br>
   * <code>Sprite.TRANS_NONE</code> - causes the specified image region to be copied unchanged<br>
   * <code>Sprite.TRANS_ROT90</code> - causes the specified image region to be rotated clockwise by
   * 90 degrees.<br>
   * <code>Sprite.TRANS_ROT180</code> - causes the specified image region to be rotated clockwise by
   * 180 degrees.<br>
   * <code>Sprite.TRANS_ROT270</code> - causes the specified image region to be rotated clockwise by
   * 270 degrees.<br>
   * <code>Sprite.TRANS_MIRROR</code> - causes the specified image region to be reflected about its
   * vertical center.<br>
   * <code>Sprite.TRANS_MIRROR_ROT90</code> - causes the specified image region to be reflected
   * about its vertical center and then rotated clockwise by 90 degrees.<br>
   * <code>Sprite.TRANS_MIRROR_ROT180</code> - causes the specified image region to be reflected
   * about its vertical center and then rotated clockwise by 180 degrees.<br>
   * <code>Sprite.TRANS_MIRROR_ROT270</code> - causes the specified image region to be reflected
   * about its vertical center and then rotated clockwise by 270 degrees.<br>
   *
   * <p>The size of the returned image will be the size of the specified region with the transform
   * applied. For example, if the region is <code>100&nbsp;x&nbsp;50</code> pixels and the transform
   * is <code>TRANS_ROT90</code>, the returned image will be <code>50&nbsp;x&nbsp;100</code> pixels.
   *
   * <p><strong>Note:</strong> If all of the following conditions are met, this method may simply
   * return the source <code>Image</code> without creating a new one:
   *
   * <ul>
   *   <li>the source image is immutable;
   *   <li>the region represents the entire source image; and
   *   <li>the transform is <code>TRANS_NONE</code>.
   * </ul>
   *
   * @param dataSource the source image data to be copied from
   * @param x the horizontal location of the region to be copied
   * @param y the vertical location of the region to be copied
   * @param width the width of the region to be copied
   * @param height the height of the region to be copied
   * @param transform the transform to be applied to the region
   * @return the new immutable image data
   */
  public ImageData createImmutableImageData(
      ImageData dataSource, int x, int y, int width, int height, int transform) {
    ImageData dataDest;

    if ((transform & Image.TRANSFORM_SWAP_AXIS) != 0x0) {
      dataDest = new ImageData(height, width, false);
    } else {
      dataDest = new ImageData(width, height, false);
    }

    // Copy native data from the source region
    try {
      createImmutableImageDataRegion(
          dataDest, dataSource, x, y, width, height, transform, dataSource.isMutable());
    } catch (OutOfMemoryError e) {
      garbageCollectImages(false);

      try {
        createImmutableImageDataRegion(
            dataDest, dataSource, x, y, width, height, transform, dataSource.isMutable());
      } catch (OutOfMemoryError e2) {
        garbageCollectImages(true);

        createImmutableImageDataRegion(
            dataDest, dataSource, x, y, width, height, transform, dataSource.isMutable());
      }
    }

    return dataDest;
  }
  /** Loads the resources */
  void initResources() {
    final Class<ControlExample> clazz = ControlExample.class;
    if (resourceBundle != null) {
      try {
        if (images == null) {
          images = new Image[imageLocations.length];

          for (int i = 0; i < imageLocations.length; ++i) {
            InputStream sourceStream = clazz.getResourceAsStream(imageLocations[i]);
            ImageData source = new ImageData(sourceStream);
            if (imageTypes[i] == SWT.ICON) {
              ImageData mask = source.getTransparencyMask();
              images[i] = new Image(null, source, mask);
            } else {
              images[i] = new Image(null, source);
            }
            try {
              sourceStream.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        return;
      } catch (Throwable t) {
      }
    }
    String error =
        (resourceBundle != null)
            ? getResourceString("error.CouldNotLoadResources")
            : "Unable to load resources"; //$NON-NLS-1$
    freeResources();
    throw new RuntimeException(error);
  }
Esempio n. 3
0
  public static void preprocess(Map<String, ImageData> images) throws IOException {
    File cacheFile = new File(colorHistCacheFile);
    if (cacheFile.exists()) {
      try (BufferedReader br = new BufferedReader(new FileReader(colorHistCacheFile))) {
        String line = br.readLine();

        while (line != null) {
          double[] bins = new double[dim * dim * dim];
          String key = line.substring(0, line.indexOf(" "));
          String values = line.substring(line.indexOf("[") + 1, line.indexOf("]"));
          String binS[] = values.split(",\\s");
          for (int i = 0; i < binS.length; i++) {
            bins[i] = Double.parseDouble(binS[i]);
          }
          images.get(key).setColorHistogram(bins);
          line = br.readLine();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      try (BufferedWriter bw = new BufferedWriter(new FileWriter(colorHistCacheFile))) {
        for (ImageData id : images.values()) {
          double[] colorHistogram = getHist(id);
          id.setColorHistogram(colorHistogram);

          String line = String.format("%s %s%n", id.getFilename(), Arrays.toString(colorHistogram));
          bw.write(line);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  public static BufferedImage convertImageData(ImageData data) {
    BufferedImage bimg = null;
    int height = data.getHeight(), width = data.getWidth();
    Object pixels = data.getData();
    if (pixels instanceof int[] && data.getElementWidth() == 1) {
      int[] arr = (int[]) pixels;
      byte[] barray = new byte[arr.length * 3];
      int k = 0;
      for (int j = 0; j < arr.length; j++) {
        int l = arr[j];
        barray[k++] = (byte) (l & 0xFF);
        barray[k++] = (byte) ((l >>> 8) & 0xFF);
        barray[k++] = (byte) ((l >>> 16) & 0xFF);
      }
      ColorModel ccm =
          new ComponentColorModel(
              ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_sRGB),
              new int[] {8, 8, 8},
              false,
              false,
              Transparency.OPAQUE,
              DataBuffer.TYPE_BYTE);
      DataBuffer bbuf = new DataBufferByte(barray, barray.length);
      SampleModel bmodel =
          new PixelInterleavedSampleModel(
              DataBuffer.TYPE_BYTE, width, height, 3, 3 * width, new int[] {2, 1, 0});

      WritableRaster raster = Raster.createWritableRaster(bmodel, bbuf, new Point(0, 0));
      bimg = new BufferedImage(ccm, raster, false, new Hashtable());
    } else if (pixels instanceof byte[]
        && data.getElementWidth() == 1) { // Assume gray scale model?
      byte[] arr = (byte[]) pixels;
      byte[] barray = new byte[arr.length * 3];
      int k = 0;
      for (int j = 0; j < arr.length; j++) {
        byte l = arr[j];
        barray[k++] = l;
        barray[k++] = l;
        barray[k++] = l;
      }
      ColorModel ccm =
          new ComponentColorModel(
              ICC_ColorSpace.getInstance(ICC_ColorSpace.CS_sRGB),
              new int[] {8, 8, 8},
              false,
              false,
              Transparency.OPAQUE,
              DataBuffer.TYPE_BYTE);
      DataBuffer bbuf = new DataBufferByte(barray, barray.length);
      SampleModel bmodel =
          new PixelInterleavedSampleModel(
              DataBuffer.TYPE_BYTE, width, height, 3, 3 * width, new int[] {2, 1, 0});

      WritableRaster raster = Raster.createWritableRaster(bmodel, bbuf, new Point(0, 0));
      bimg = new BufferedImage(ccm, raster, false, new Hashtable());
    } else {
      throw new RuntimeException("Unexpected data.");
    }
    return bimg;
  }
Esempio n. 5
0
  protected void findImages(boolean internal, int howMany, LinkedList<ImageData> foundImages) {
    Uri uri =
        internal
            ? MediaStore.Images.Media.INTERNAL_CONTENT_URI
            : MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String[] projection = {
      MediaStore.Images.Media.DATA,
      MediaStore.Images.Media.ORIENTATION,
      MediaStore.Images.Media.BUCKET_ID,
      MediaStore.Images.Media.BUCKET_DISPLAY_NAME
    };
    String selection = "";
    for (String id : getFoundAlbums()) {
      if (isInternalId(id) == internal && mSettings.isAlbumEnabled(id)) {
        String[] parts = id.split(":");
        if (parts.length > 1) {
          if (selection.length() > 0) {
            selection += " OR ";
          }
          selection += MediaStore.Images.Media.BUCKET_ID + " = '" + parts[1] + "'";
        }
      }
    }
    if (selection.isEmpty()) {
      return;
    }
    Cursor cursor = mResolver.query(uri, projection, selection, null, null);
    if (cursor != null) {
      int dataIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);

      if (cursor.getCount() > howMany && mLastPosition == INVALID) {
        mLastPosition = pickRandomStart(cursor.getCount(), howMany);
      }
      cursor.moveToPosition(mLastPosition);

      if (dataIndex < 0) {
        log(TAG, "can't find the DATA column!");
      } else {
        while (foundImages.size() < howMany && cursor.moveToNext()) {
          ImageData data = unpackImageData(cursor, null);
          data.uri = uri;
          foundImages.offer(data);
          mLastPosition = cursor.getPosition();
        }
        if (cursor.isAfterLast()) {
          mLastPosition = -1;
        }
        if (cursor.isBeforeFirst()) {
          mLastPosition = INVALID;
        }
      }

      cursor.close();
    }
  }
 /**
  * Returns an {@link Image} encoded by the specified {@link InputStream}.
  *
  * @param stream the {@link InputStream} encoding the image data
  * @return the {@link Image} encoded by the specified input stream
  */
 protected static Image getImage(InputStream stream) throws IOException {
   try {
     Display display = Display.getCurrent();
     ImageData data = new ImageData(stream);
     if (data.transparentPixel > 0) {
       return new Image(display, data, data.getTransparencyMask());
     }
     return new Image(display, data);
   } finally {
     stream.close();
   }
 }
 public void testModifyData() throws Exception {
   ImageData originalData = getImageData(Fixture.IMAGE1);
   Image image = ResourceFactory.findImage(originalData);
   cache.putImageData(image, originalData);
   ImageData copyData1 = cache.getImageData(image);
   assertNotSame(originalData, copyData1);
   assertEqualsImageData(originalData, copyData1);
   // modify original data
   originalData.setPixel(0, 0, 23);
   ImageData copyData2 = cache.getImageData(image);
   assertNotSame(copyData1, copyData2);
   assertEqualsImageData(copyData1, copyData2);
 }
Esempio n. 8
0
 /**
  * Select the image data from the database
  *
  * @param imageName the name of the image
  * @return <code>null</code> if no data was found
  * @throws Exception
  */
 public ImageData selectImage(String imageName) throws Exception {
   ImageData imageData = new ImageData(imageName);
   fSelectImage.setString(1, imageName);
   ResultSet resultSet = fSelectImage.executeQuery();
   try {
     while (resultSet.next()) {
       imageData.setUrl(resultSet.getString(1));
       imageData.setFilename(resultSet.getString(2));
       return imageData;
     }
   } finally {
     resultSet.close();
   }
   return null;
 }
Esempio n. 9
0
  /**
   * Run the ImageData getThumbnail() method test.
   *
   * @throws Exception
   */
  @Test
  public void testGetThumbnail() throws Exception {
    Images fixture = new Images();
    fixture.setThumbnail(new ImageData());
    fixture.setLowResolution(new ImageData());
    fixture.setStandardResolution(new ImageData());

    ImageData result = fixture.getThumbnail();

    // add additional test code here
    assertNotNull(result);
    assertEquals("ImageData [imageHeight=0, imageUrl=null, imageWidth=0]", result.toString());
    assertEquals(null, result.getImageUrl());
    assertEquals(0, result.getImageHeight());
    assertEquals(0, result.getImageWidth());
  }
Esempio n. 10
0
  private static double[] getHist(ImageData queryImage) throws IOException {
    BufferedImage image = queryImage.getImage();
    int imHeight = image.getHeight();
    int imWidth = image.getWidth();
    double[] bins = new double[dim * dim * dim];
    int step = 256 / dim;
    Raster raster = image.getRaster();
    for (int i = 0; i < imWidth; i++) {
      for (int j = 0; j < imHeight; j++) {
        // rgb->ycrcb
        int r = raster.getSample(i, j, 0);
        int g = raster.getSample(i, j, 1);
        int b = raster.getSample(i, j, 2);

        // Changed Codes.
        int y = (int) (0 + 0.299 * r + 0.587 * g + 0.114 * b);
        int cb = (int) (128 - 0.16874 * r - 0.33126 * g + 0.50000 * b);
        int cr = (int) (128 + 0.50000 * r - 0.41869 * g - 0.08131 * b);

        int ybin = y / step;
        int cbbin = cb / step;
        int crbin = cr / step;

        // Changed Codes.
        bins[ybin * dim * dim + cbbin * dim + crbin]++;
      }
    }

    // Changed Codes.
    for (int i = 0; i < dim * dim * dim; i++) {
      bins[i] = bins[i] / (imHeight * imWidth);
    }
    return bins;
  }
Esempio n. 11
0
  public ImagePanel(ImageData aThumbnail) {
    itsThumbnail = aThumbnail;

    setLayout(new BorderLayout());
    add(new JLabel(aThumbnail != null ? aThumbnail.getName() : ""), BorderLayout.NORTH);
    add(new ThumbnailPanel(itsThumbnail), BorderLayout.CENTER);
  }
Esempio n. 12
0
  @Override
  protected ImageData unpackImageData(Cursor cursor, ImageData data) {
    if (data == null) {
      data = new ImageData();
    }
    int dataIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
    int orientationIndex = cursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION);
    int bucketIndex = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_ID);

    data.url = cursor.getString(dataIndex);
    data.albumId = cursor.getString(bucketIndex);
    data.position = UNINITIALIZED;
    data.cursor = null;
    data.orientation = cursor.getInt(orientationIndex);

    return data;
  }
 public void updateVertex(
     final Dimension size, final Insets margin, final Insets border, final Insets padding) {
   this.m_entity.setVisible(true);
   this.m_entity3D.setVisible(true);
   this.m_particleEntity.setVisible(true);
   final int left = margin.left + border.left + padding.left;
   final int bottom = margin.bottom + border.bottom + padding.bottom;
   this.m_entity.getTransformer().setTranslation(0, this.m_x, this.m_y);
   if (this.m_modulationColor != null) {
     this.m_entity3D.setColor(
         this.m_modulationColor.getRed(),
         this.m_modulationColor.getGreen(),
         this.m_modulationColor.getBlue(),
         this.m_modulationColor.getAlpha());
     for (int i = 0, isize = this.m_textDataList.size(); i < isize; ++i) {
       this.m_textDataList
           .get(i)
           .getParticle()
           .setGlobalColor(
               this.m_modulationColor.getRed() * this.m_modulationColor.getAlpha(),
               this.m_modulationColor.getGreen() * this.m_modulationColor.getAlpha(),
               this.m_modulationColor.getBlue() * this.m_modulationColor.getAlpha(),
               this.m_modulationColor.getAlpha());
     }
   } else {
     this.m_entity3D.setColor(1.0f, 1.0f, 1.0f, 1.0f);
     for (int i = 0, isize = this.m_textDataList.size(); i < isize; ++i) {
       this.m_textDataList.get(i).getParticle().setGlobalColor(1.0f, 1.0f, 1.0f, 1.0f);
     }
   }
   for (int i = 0, listSize = this.m_imageDataList.size(); i < listSize; ++i) {
     final ImageData imageData = this.m_imageDataList.get(i);
     final int x = imageData.getX() * this.m_chunkWidth + left;
     final int y = imageData.getY() * this.m_chunkHeight + bottom + size.height;
     final GeometrySprite geometry = (GeometrySprite) this.m_entity3D.getGeometry(i);
     geometry.setTopLeft(y, x);
   }
   for (int i = 0, listSize = this.m_textDataList.size(); i < listSize; ++i) {
     final TextData textData = this.m_textDataList.get(i);
     final GeometryMesh geom =
         (GeometryMesh) this.m_entity3D.getGeometry(i + this.m_imageDataList.size());
     this.setTextGeometryPosition(geom.getVertexBuffer(), textData);
   }
 }
 private void addGeometry(final ImageData data) {
   final GeometrySprite geom =
       ((MemoryObject.ObjectFactory<GeometrySprite>) GLGeometrySprite.Factory).newPooledInstance();
   final Pixmap pixmap = data.getPixmap();
   geom.setTextureCoordinates(
       pixmap.getTop(), pixmap.getLeft(), pixmap.getBottom(), pixmap.getRight());
   geom.setSize(pixmap.getWidth(), pixmap.getHeight());
   this.m_entity3D.addTexturedGeometry(geom, pixmap.getTexture(), null);
   geom.removeReference();
 }
Esempio n. 15
0
  /**
   * Creates an immutable image from a source mutable image.
   *
   * <p>This method is useful for placing the contents of mutable images into <code>Choice</code>
   * objects. The application can create an off-screen image using the {@link #createImage(int, int)
   * createImage(w, h)} method, draw into it using a <code>Graphics</code> object obtained with the
   * {@link #getGraphics() getGraphics()} method, and then create an immutable copy of it with this
   * method. The immutable copy may then be placed into <code>Choice</code> objects.
   *
   * @param mutableSource the source mutable image to be copied
   * @return the new immutable image
   */
  public ImageData createImmutableCopy(ImageData mutableSource) {
    ImageData data = new ImageData(mutableSource.getWidth(), mutableSource.getHeight(), false);

    // Duplicate mutable image contents
    try {
      createImmutableImageDataCopy(data, mutableSource);
    } catch (OutOfMemoryError e) {
      garbageCollectImages(false);

      try {
        createImmutableImageDataCopy(data, mutableSource);
      } catch (OutOfMemoryError e2) {
        garbageCollectImages(true);

        createImmutableImageDataCopy(data, mutableSource);
      }
    }

    return data;
  }
Esempio n. 16
0
 protected ImageData getImageData(Object image) {
   ImageData imageData = new ImageData();
   if (image instanceof ImageResource) {
     ImageResource imageResource = (ImageResource) image;
     imageData.height = imageResource.getHeight();
     imageData.width = imageResource.getWidth();
   } else if (image instanceof ComposedImage) {
     ComposedImage composedImage = (ComposedImage) image;
     List<ComposedImage.Size> sizes = new ArrayList<ComposedImage.Size>();
     List<Object> images = new ArrayList<Object>(composedImage.getImages());
     List<ImageData> nestedImagesData = new ArrayList<ImageData>();
     for (Object nestedImage : images) {
       ImageData nestedImageData = getImageData(nestedImage);
       ComposedImage.Size size = new ComposedImage.Size();
       size.height = nestedImageData.height;
       size.width = nestedImageData.width;
       sizes.add(size);
       nestedImagesData.add(nestedImageData);
     }
   }
   return imageData;
 }
Esempio n. 17
0
 @Override
 protected void findPosition(ImageData data) {
   if (data.position == -1) {
     if (data.cursor == null) {
       openCursor(data);
     }
     if (data.cursor != null) {
       int dataIndex = data.cursor.getColumnIndex(MediaStore.Images.Media.DATA);
       data.cursor.moveToPosition(-1);
       while (data.position == -1 && data.cursor.moveToNext()) {
         String url = data.cursor.getString(dataIndex);
         if (url != null && url.equals(data.url)) {
           data.position = data.cursor.getPosition();
         }
       }
       if (data.position == -1) {
         // oops!  The image isn't in this album. How did we get here?
         data.position = INVALID;
       }
     }
   }
 }
Esempio n. 18
0
  public void parse() {
    try {
      // parsing all images and populating imageData object
      for (int i = 0; i < images.length(); i++) {
        JSONObject jsonObject = images.getJSONObject(i);

        String imageUrlThumbnail =
            jsonObject.getJSONObject(TAG_IMAGES).getJSONObject(TAG_THUMBNAIL).getString(TAG_URL);
        if (imageData.isInCache(imageUrlThumbnail)) continue;

        String imageUrlStdRes =
            jsonObject
                .getJSONObject(TAG_IMAGES)
                .getJSONObject(TAG_STD_RESOLUTION)
                .getString(TAG_URL);

        String caption = jsonObject.getJSONObject(TAG_CAPTION).getString(TAG_TEXT);

        JSONObject user = jsonObject.getJSONObject(TAG_USER);
        String username = user.getString(TAG_USERNAME);
        String full_name = user.getString(TAG_FULL_NAME);

        // tmp hashmap for single image
        ConcurrentHashMap<String, String> image = new ConcurrentHashMap<>();

        // adding each child node to HashMap
        image.put(TAG_USERNAME, username);
        image.put(TAG_FULL_NAME, full_name);
        image.put(TAG_CAPTION, caption);
        image.put(TAG_LINK_THUMB, imageUrlThumbnail);
        image.put(TAG_LINK_STD_RES, imageUrlStdRes);

        imageData.addImageData(image);
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Esempio n. 19
0
  @Override
  protected void openCursor(ImageData data) {
    log(TAG, "opening single album");

    String[] projection = {
      MediaStore.Images.Media.DATA,
      MediaStore.Images.Media.ORIENTATION,
      MediaStore.Images.Media.BUCKET_ID,
      MediaStore.Images.Media.BUCKET_DISPLAY_NAME
    };
    String selection = MediaStore.Images.Media.BUCKET_ID + " = '" + data.albumId + "'";

    data.cursor = mResolver.query(data.uri, projection, selection, null, null);
  }
Esempio n. 20
0
 @Override
 protected void paintComponent(Graphics aG) {
   super.paintComponent(aG);
   itsThumbnail.paintThumbnail(aG);
 }
 public String type() {
   return ImageData.ice_staticId();
 }
Esempio n. 22
0
  @Override
  public Image run(Image input, int imageType) {

    ImageData inData = input.getImageData(); // Die echten Bilddaten sind hier drin

    // RGB zu YUV Umwandlungsmatrix
    //		double[] linear_conversion = {
    //			0.2126, 0.7152, 0.0722,
    //			-0.09991, -0.33609, 0.436,
    //			0.615, -0.55861, -0.05639
    //		};
    double[] linear_conversion = {0.299, 0.587, 0.114, -0.147, -0.289, 0.436, 0.615, -0.515, -0.1};
    Matrix m = new Matrix(3, 3, linear_conversion);

    // YUV zu RGB Umwandlungmatrix (das Inverse)
    //		double[] inv_linear_conversion = {
    //		    1.0000,    0.0000,    1.28033,
    //		    1.0000,   -0.21482,   -0.38059,
    //		    1.0000,    2.12798,   -0.0005
    //		};
    double[] inv_linear_conversion = {
      1.0000, 0.0000, 1.1398, 1.0000, -0.3946, -0.5805, 1.0000, 2.0320, -0.0005
    };
    Matrix minv = new Matrix(3, 3, inv_linear_conversion);

    for (int v = 0; v < inData.height; v++) {
      for (int u = 0; u < inData.width; u++) {
        int pixel = inData.getPixel(u, v);

        RGB rgb = inData.palette.getRGB(pixel);

        // Variante mit Farbwerte U und V von YUV auf 0 setzen
        Vector r = new Vector(rgb.red, rgb.green, rgb.blue);
        double[] y = m.times(r).getV();
        y[2] = 0;
        y[1] = 0;
        r = minv.times(new Vector(y));
        rgb.red = (int) r.x(1);
        rgb.green = (int) r.x(2);
        rgb.blue = (int) r.x(3);

        if (rgb.red < 0) rgb.red = 0;
        else if (rgb.red > 255) rgb.red = 255;

        if (rgb.green < 0) rgb.green = 0;
        else if (rgb.green > 255) rgb.green = 255;

        if (rgb.blue < 0) rgb.blue = 0;
        else if (rgb.blue > 255) rgb.blue = 255;

        // Variante mit der Sättigung auf 0 gesetzt (schlechter)
        //				float[] hsb = inData.palette.getRGB(pixel).getHSB();
        //
        //				hsb[1] = 0; //Sättigung auf 0 setzen
        //
        //				Color c = new Color(Color.HSBtoRGB(hsb[0],hsb[1],hsb[2]));
        //				RGB rgb = new RGB(0,0,0);
        //				rgb.red = c.getRed();
        //				rgb.green = c.getGreen();
        //				rgb.blue = c.getBlue();

        inData.setPixel(u, v, inData.palette.getPixel(rgb));
      }
    }
    return new Image(input.getDevice(), inData);
  }
 @Override
 ImageData[] loadFromByteStream() {
   int[] fileHeader = loadFileHeader();
   byte[] infoHeader = new byte[BMPHeaderFixedSize];
   try {
     inputStream.read(infoHeader);
   } catch (Exception e) {
     SWT.error(SWT.ERROR_IO, e);
   }
   int width =
       (infoHeader[4] & 0xFF)
           | ((infoHeader[5] & 0xFF) << 8)
           | ((infoHeader[6] & 0xFF) << 16)
           | ((infoHeader[7] & 0xFF) << 24);
   int height =
       (infoHeader[8] & 0xFF)
           | ((infoHeader[9] & 0xFF) << 8)
           | ((infoHeader[10] & 0xFF) << 16)
           | ((infoHeader[11] & 0xFF) << 24);
   if (height < 0) height = -height;
   int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8);
   this.compression =
       (infoHeader[16] & 0xFF)
           | ((infoHeader[17] & 0xFF) << 8)
           | ((infoHeader[18] & 0xFF) << 16)
           | ((infoHeader[19] & 0xFF) << 24);
   PaletteData palette = loadPalette(infoHeader);
   if (inputStream.getPosition() < fileHeader[4]) {
     // Seek to the specified offset
     try {
       inputStream.skip(fileHeader[4] - inputStream.getPosition());
     } catch (IOException e) {
       SWT.error(SWT.ERROR_IO, e);
     }
   }
   byte[] data = loadData(infoHeader);
   this.importantColors =
       (infoHeader[36] & 0xFF)
           | ((infoHeader[37] & 0xFF) << 8)
           | ((infoHeader[38] & 0xFF) << 16)
           | ((infoHeader[39] & 0xFF) << 24);
   int xPelsPerMeter =
       (infoHeader[24] & 0xFF)
           | ((infoHeader[25] & 0xFF) << 8)
           | ((infoHeader[26] & 0xFF) << 16)
           | ((infoHeader[27] & 0xFF) << 24);
   int yPelsPerMeter =
       (infoHeader[28] & 0xFF)
           | ((infoHeader[29] & 0xFF) << 8)
           | ((infoHeader[30] & 0xFF) << 16)
           | ((infoHeader[31] & 0xFF) << 24);
   this.pelsPerMeter = new Point(xPelsPerMeter, yPelsPerMeter);
   int type =
       (this.compression == 1 /*BMP_RLE8_COMPRESSION*/)
               || (this.compression == 2 /*BMP_RLE4_COMPRESSION*/)
           ? SWT.IMAGE_BMP_RLE
           : SWT.IMAGE_BMP;
   return new ImageData[] {
     ImageData.internal_new(
         width, height, bitCount, palette, 4, data, 0, null, null, -1, -1, type, 0, 0, 0, 0)
   };
 }
Esempio n. 24
0
 public void updateImage(ImageData imageData) throws Exception {
   fUpdateTopicContent.setString(1, imageData.getUrl());
   fUpdateTopicContent.setString(2, imageData.getFilename());
   fUpdateTopicContent.setString(3, imageData.getName());
   fUpdateTopicContent.execute();
 }
Esempio n. 25
0
 public void insertImage(ImageData imageData) throws Exception {
   fInsertImage.setString(1, imageData.getName());
   fInsertImage.setString(2, imageData.getUrl());
   fInsertImage.setString(3, imageData.getFilename());
   fInsertImage.execute();
 }
 /**
  * Return a DeviceIndependentImage representing the image block at the current position in the
  * input stream. Throw an error if an error occurs.
  */
 ImageData readImageBlock(PaletteData defaultPalette) {
   int depth;
   PaletteData palette;
   byte[] block = new byte[9];
   try {
     inputStream.read(block);
   } catch (IOException e) {
     SWT.error(SWT.ERROR_IO, e);
   }
   int left = (block[0] & 0xFF) | ((block[1] & 0xFF) << 8);
   int top = (block[2] & 0xFF) | ((block[3] & 0xFF) << 8);
   int width = (block[4] & 0xFF) | ((block[5] & 0xFF) << 8);
   int height = (block[6] & 0xFF) | ((block[7] & 0xFF) << 8);
   byte bitField = block[8];
   boolean interlaced = (bitField & 0x40) != 0;
   // boolean sorted = (bitField & 0x20) != 0;
   if ((bitField & 0x80) != 0) {
     // Local palette.
     depth = (bitField & 0x7) + 1;
     palette = readPalette(1 << depth);
   } else {
     // No local palette.
     depth = defaultDepth;
     palette = defaultPalette;
   }
   /* Work around: Ignore the case where a GIF specifies an
    * invalid index for the transparent pixel that is larger
    * than the number of entries in the palette. */
   if (transparentPixel > 1 << depth) {
     transparentPixel = -1;
   }
   // Promote depth to next highest supported value.
   if (!(depth == 1 || depth == 4 || depth == 8)) {
     if (depth < 4) depth = 4;
     else depth = 8;
   }
   if (palette == null) {
     palette = grayRamp(1 << depth);
   }
   int initialCodeSize = -1;
   try {
     initialCodeSize = inputStream.read();
   } catch (IOException e) {
     SWT.error(SWT.ERROR_IO, e);
   }
   if (initialCodeSize < 0) {
     SWT.error(SWT.ERROR_INVALID_IMAGE);
   }
   ImageData image =
       ImageData.internal_new(
           width,
           height,
           depth,
           palette,
           4,
           null,
           0,
           null,
           null,
           -1,
           transparentPixel,
           SWT.IMAGE_GIF,
           left,
           top,
           disposalMethod,
           delayTime);
   LZWCodec codec = new LZWCodec();
   codec.decode(inputStream, loader, image, interlaced, initialCodeSize);
   return image;
 }
Esempio n. 27
0
  public static void main(String[] args) {
    final Display display = new Display();
    final Image image = display.getSystemImage(SWT.ICON_INFORMATION);
    final Shell shell = new Shell(display, SWT.NO_TRIM);
    Region region = new Region();
    final ImageData imageData = image.getImageData();
    if (imageData.alphaData != null) {
      Rectangle pixel = new Rectangle(0, 0, 1, 1);
      for (int y = 0; y < imageData.height; y++) {
        for (int x = 0; x < imageData.width; x++) {
          if (imageData.getAlpha(x, y) == 255) {
            pixel.x = imageData.x + x;
            pixel.y = imageData.y + y;
            region.add(pixel);
          }
        }
      }
    } else {
      ImageData mask = imageData.getTransparencyMask();
      Rectangle pixel = new Rectangle(0, 0, 1, 1);
      for (int y = 0; y < mask.height; y++) {
        for (int x = 0; x < mask.width; x++) {
          if (mask.getPixel(x, y) != 0) {
            pixel.x = imageData.x + x;
            pixel.y = imageData.y + y;
            region.add(pixel);
          }
        }
      }
    }
    shell.setRegion(region);

    Listener l =
        new Listener() {
          /** The x/y of the MouseDown, relative to top-left of the shell. */
          int startX, startY;

          @Override
          public void handleEvent(Event e) {
            if (e.type == SWT.KeyDown && e.character == SWT.ESC) {
              shell.dispose();
            }
            if (e.type == SWT.MouseDown && e.button == 1) {
              Point p = shell.toDisplay(e.x, e.y);
              Point loc = shell.getLocation();
              startX = p.x - loc.x;
              startY = p.y - loc.y;
            }
            if (e.type == SWT.MouseMove && (e.stateMask & SWT.BUTTON1) != 0) {
              Point p = shell.toDisplay(e.x, e.y);
              p.x -= startX;
              p.y -= startY;
              shell.setLocation(p);
            }
            if (e.type == SWT.Paint) {
              e.gc.drawImage(image, imageData.x, imageData.y);
            }
          }
        };
    shell.addListener(SWT.KeyDown, l);
    shell.addListener(SWT.MouseDown, l);
    shell.addListener(SWT.MouseMove, l);
    shell.addListener(SWT.Paint, l);

    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) display.sleep();
    }
    region.dispose();
    image.dispose();
    display.dispose();
  }