Java Code Examples for java.awt.image.BufferedImage#setRGB()

The following examples show how to use java.awt.image.BufferedImage#setRGB() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * <p>Writes a rectangular area of pixels in the destination
 * <code>BufferedImage</code>. Calling this method on
 * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
 * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
 *
 * @param img the destination image
 * @param x the x location at which to start storing pixels
 * @param y the y location at which to start storing pixels
 * @param w the width of the rectangle of pixels to store
 * @param h the height of the rectangle of pixels to store
 * @param pixels an array of pixels, stored as integers
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and
 *   of length &lt; w*h
 */
public static void setPixels(BufferedImage img,
                             int x, int y, int w, int h, int[] pixels) {
    if (pixels == null || w == 0 || h == 0) {
        return;
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length" +
                                           " >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_INT_ARGB ||
        imageType == BufferedImage.TYPE_INT_RGB) {
        WritableRaster raster = img.getRaster();
        raster.setDataElements(x, y, w, h, pixels);
    } else {
        // Unmanages the image
        img.setRGB(x, y, w, h, pixels, 0, w);
    }
}
 
Example 2
Source Project: springboot-pay-example   File: PayUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据url生成二位图片对象
 *
 * @param codeUrl
 * @return
 * @throws WriterException
 */
public static BufferedImage getQRCodeImge(String codeUrl) throws WriterException {
    Map<EncodeHintType, Object> hints = new Hashtable();
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
    int width = 256;
    BitMatrix bitMatrix = (new MultiFormatWriter()).encode(codeUrl, BarcodeFormat.QR_CODE, width, width, hints);
    BufferedImage image = new BufferedImage(width, width, 1);
    for(int x = 0; x < width; ++x) {
        for(int y = 0; y < width; ++y) {
            image.setRGB(x, y, bitMatrix.get(x, y) ? -16777216 : -1);
        }
    }

    return image;
}
 
Example 3
Source Project: pyramid   File: KMeansTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void plot(Vector vector, int height, int width, String imageFile) throws Exception{

        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//        Graphics2D g2d = image.createGraphics();
//        g2d.setBackground(Color.WHITE);
//
//
//        g2d.fillRect ( 0, 0, image.getWidth(), image.getHeight() );
//        g2d.dispose();
        for (int i=0;i<width;i++){
            for (int j=0;j<height;j++){
                int v = (int)(vector.get(i*width+j));
                int rgb = 65536 * v + 256 * v + v;
                image.setRGB(j,i,rgb);
//                image.setRGB(j,i,(int)(vector.get(i*width+j)/255*16777215));
            }
        }


        new File(imageFile).getParentFile().mkdirs();
        ImageIO.write(image,"png",new File(imageFile));
    }
 
Example 4
public static FastBitmap cifar10InstanceToBitmap(final Instance instance) {
	final BufferedImage image = new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB);
	final double[] imageValues = instance.toDoubleArray();
	for (int i = 0; i < 32; i++) {
		for (int j = 0; j < 32; j++) {
			final int offset = (i + 1);
			final int a = 255;
			final int r = (int) imageValues[offset * j];
			final int g = (int) imageValues[1024 + offset * j];
			final int b = (int) imageValues[2048 + offset * j];
			int p = 0;
			p = p | (a << 24);
			p = p | (r << 16);
			p = p | (g << 8);
			p = p | b;
			image.setRGB(i, j, p);
		}
	}
	return new FastBitmap(image);
}
 
Example 5
Source Project: pdfbox-layout   File: ExampleTest.java    License: MIT License 6 votes vote down vote up
public static BufferedImage compareImage(final BufferedImage img1,
    final BufferedImage img2) throws IOException {

final int w = img1.getWidth();
final int h = img1.getHeight();
final int[] p1 = img1.getRGB(0, 0, w, h, null, 0, w);
final int[] p2 = img2.getRGB(0, 0, w, h, null, 0, w);

if (!(java.util.Arrays.equals(p1, p2))) {
    for (int i = 0; i < p1.length; i++) {
	if (p1[i] != p2[i]) {
	    p1[i] = Color.red.getRGB();
	}
    }
    final BufferedImage out = new BufferedImage(w, h,
	    BufferedImage.TYPE_INT_ARGB);
    out.setRGB(0, 0, w, h, p1, 0, w);
    return out;
}
return null;
   }
 
Example 6
/**
 * <p>Writes a rectangular area of pixels in the destination
 * <code>BufferedImage</code>. Calling this method on
 * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
 * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
 *
 * @param img the destination image
 * @param x the x location at which to start storing pixels
 * @param y the y location at which to start storing pixels
 * @param w the width of the rectangle of pixels to store
 * @param h the height of the rectangle of pixels to store
 * @param pixels an array of pixels, stored as integers
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and
 *   of length &lt; w*h
 */
public static void setPixels(BufferedImage img,
                             int x, int y, int w, int h, int[] pixels) {
    if (pixels == null || w == 0 || h == 0) {
        return;
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length" +
                                           " >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_INT_ARGB ||
        imageType == BufferedImage.TYPE_INT_RGB) {
        WritableRaster raster = img.getRaster();
        raster.setDataElements(x, y, w, h, pixels);
    } else {
        // Unmanages the image
        img.setRGB(x, y, w, h, pixels, 0, w);
    }
}
 
Example 7
Source Project: TGAReader   File: TGASwingBufferedImage.java    License: MIT License 6 votes vote down vote up
private static JLabel createTGALabel(String path) throws IOException {
	
	FileInputStream fis = new FileInputStream(path);
	byte [] buffer = new byte[fis.available()];
	fis.read(buffer);
	fis.close();
	
	int [] pixels = TGAReader.read(buffer, TGAReader.ARGB);
	int width = TGAReader.getWidth(buffer);
	int height = TGAReader.getHeight(buffer);
	BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
	image.setRGB(0, 0, width, height, pixels, 0, width);
	
	ImageIcon icon = new ImageIcon(image.getScaledInstance(128, 128, BufferedImage.SCALE_SMOOTH));
	return new JLabel(icon);
}
 
Example 8
/**
 * <p>Writes a rectangular area of pixels in the destination
 * <code>BufferedImage</code>. Calling this method on
 * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
 * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
 *
 * @param img the destination image
 * @param x the x location at which to start storing pixels
 * @param y the y location at which to start storing pixels
 * @param w the width of the rectangle of pixels to store
 * @param h the height of the rectangle of pixels to store
 * @param pixels an array of pixels, stored as integers
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and
 *   of length &lt; w*h
 */
public static void setPixels(BufferedImage img,
                             int x, int y, int w, int h, int[] pixels) {
    if (pixels == null || w == 0 || h == 0) {
        return;
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length" +
                                           " >= w*h");
    }

    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_INT_ARGB ||
        imageType == BufferedImage.TYPE_INT_RGB) {
        WritableRaster raster = img.getRaster();
        raster.setDataElements(x, y, w, h, pixels);
    } else {
        // Unmanages the image
        img.setRGB(x, y, w, h, pixels, 0, w);
    }
}
 
Example 9
public BufferedImageLuminanceSource(BufferedImage image, int left,
        int top, int width, int height) {
    super(width, height);

    int sourceWidth = image.getWidth();
    int sourceHeight = image.getHeight();
    if (left + width > sourceWidth || top + height > sourceHeight) {
        throw new IllegalArgumentException(
                "Crop rectangle does not fit within image data.");
    }

    for (int y = top; y < top + height; y++) {
        for (int x = left; x < left + width; x++) {
            if ((image.getRGB(x, y) & 0xFF000000) == 0) {
                image.setRGB(x, y, 0xFFFFFFFF); // = white
            }
        }
    }

    this.image = new BufferedImage(sourceWidth, sourceHeight,
            BufferedImage.TYPE_BYTE_GRAY);
    this.image.getGraphics().drawImage(image, 0, 0, null);
    this.left = left;
    this.top = top;
}
 
Example 10
Source Project: mapwriter   File: MergeToImage.java    License: MIT License 6 votes vote down vote up
public static BufferedImage mergeRegions(RegionManager regionManager, int x, int z, int w, int h, int dimension) {
	// create the image and graphics context
	// this is the most likely place to run out of memory
	BufferedImage mergedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
	
	// copy region PNGs to the image
	for (int zi = 0; zi < h; zi += Region.SIZE) {
		for (int xi = 0; xi < w; xi += Region.SIZE) {
			//MwUtil.log("merging region (%d,%d)", rX << Mw.REGION_SHIFT, rZ << Mw.REGION_SHIFT);
			
			// get region pixels
			Region region = regionManager.getRegion(x + xi, z + zi, 0, dimension);
			int[] regionPixels = region.surfacePixels.getPixels();
			if (regionPixels != null) {
				mergedImage.setRGB(xi, zi, Region.SIZE, Region.SIZE, regionPixels, 0, Region.SIZE);
			}
		}
	}
	
	return mergedImage;
}
 
Example 11
@Override
public void generateActual(OutputStream out) throws Exception {
	BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
	for (int x = 0; x < image.getWidth(); x++) {
		for (int y = 0; y < image.getHeight(); y++) {
			image.setRGB(x, y, 0xffffffff);
		}
	}
	ImageIO.write(image, "PNG", out);
}
 
Example 12
private static Image makeIcon(long hIcon, boolean getLargeIcon) {
    if (hIcon != 0L && hIcon != -1L) {
        // Get the bits.  This has the side effect of setting the imageHash value for this object.
        int size = getLargeIcon ? 32 : 16;
        int[] iconBits = getIconBits(hIcon, size);
        if (iconBits != null) {
            BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
            img.setRGB(0, 0, size, size, iconBits, 0, size);
            return img;
        }
    }
    return null;
}
 
Example 13
Source Project: Pixie   File: Utils.java    License: MIT License 5 votes vote down vote up
/**
 * Convert a matrix into a gray scale buffered image.
 *
 * @param width - the width of the image
 * @param height - the height of the image
 * @param imageType - the type of image to create
 * @param imgMatrix - the matrix with the pixels of the image
 * @return - a buffered image, based on the input matrix
 */
public static BufferedImage convertToBuffImage(int width, int height, int imageType, double[][] imgMatrix) {
    BufferedImage bi = new BufferedImage(width, height, imageType);
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int pixel = Utils.limit(0, (int) imgMatrix[x][y], 255);
            bi.setRGB(x, y, new Color(pixel, pixel, pixel).getRGB());
        }
    }

    return bi;
}
 
Example 14
private static BufferedImage scaleImage(BufferedImage srcImgBuff,
		int width, int height, int zoomWidth, int zoomHeight) {
	int[] colorArray = srcImgBuff.getRGB(0, 0, width, height, null, 0,
			width);
	BufferedImage outBuff = new BufferedImage(zoomWidth, zoomHeight,
			BufferedImage.TYPE_INT_RGB);
	// 宽缩小的倍数
	float wScale = (float) width / zoomWidth;
	int wScaleInt = (int) (wScale + 0.5);
	// 高缩小的倍数
	float hScale = (float) height / zoomHeight;
	int hScaleInt = (int) (hScale + 0.5);
	int area = wScaleInt * hScaleInt;
	int x0, x1, y0, y1;
	int color;
	long red, green, blue;
	int x, y, i, j;
	for (y = 0; y < zoomHeight; y++) {
		// 得到原图高的Y坐标
		y0 = (int) (y * hScale);
		y1 = y0 + hScaleInt;
		for (x = 0; x < zoomWidth; x++) {
			x0 = (int) (x * wScale);
			x1 = x0 + wScaleInt;
			red = green = blue = 0;
			for (i = x0; i < x1; i++) {
				for (j = y0; j < y1; j++) {
					color = colorArray[width * j + i];
					red += getRedValue(color);
					green += getGreenValue(color);
					blue += getBlueValue(color);
				}
			}
			outBuff.setRGB(x, y, comRGB((int) (red / area),
					(int) (green / area), (int) (blue / area)));
		}
	}
	return outBuff;
}
 
Example 15
Source Project: common-project   File: QRCodeUtil.java    License: Apache License 2.0 5 votes vote down vote up
public BufferedImage toBufferedImage(BitMatrix matrix) {
    int width = matrix.getWidth();
    int height = matrix.getHeight();
    BufferedImage image = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
        }
    }
    return image;
}
 
Example 16
Source Project: geopackage-java   File: TileCreator.java    License: MIT License 4 votes vote down vote up
/**
 * Reproject the tile to the requested projection
 *
 * @param tile
 *            tile in the tile matrix projection
 * @param requestedTileWidth
 *            requested tile width
 * @param requestedTileHeight
 *            requested tile height
 * @param requestBoundingBox
 *            request bounding box in the request projection
 * @param transformRequestToTiles
 *            transformation from request to tiles
 * @param tilesBoundingBox
 *            request bounding box in the tile matrix projection
 * @return projected tile
 */
private BufferedImage reprojectTile(BufferedImage tile,
		int requestedTileWidth, int requestedTileHeight,
		BoundingBox requestBoundingBox,
		ProjectionTransform transformRequestToTiles,
		BoundingBox tilesBoundingBox) {

	final double requestedWidthUnitsPerPixel = (requestBoundingBox
			.getMaxLongitude() - requestBoundingBox.getMinLongitude())
			/ requestedTileWidth;
	final double requestedHeightUnitsPerPixel = (requestBoundingBox
			.getMaxLatitude() - requestBoundingBox.getMinLatitude())
			/ requestedTileHeight;

	final double tilesDistanceWidth = tilesBoundingBox.getMaxLongitude()
			- tilesBoundingBox.getMinLongitude();
	final double tilesDistanceHeight = tilesBoundingBox.getMaxLatitude()
			- tilesBoundingBox.getMinLatitude();

	final int width = tile.getWidth();
	final int height = tile.getHeight();

	// Tile pixels of the tile matrix tiles
	int[] pixels = new int[width * height];
	tile.getRGB(0, 0, width, height, pixels, 0, width);

	// Projected tile pixels to draw the reprojected tile
	int[] projectedPixels = new int[requestedTileWidth
			* requestedTileHeight];

	// Retrieve each pixel in the new tile from the unprojected tile
	for (int y = 0; y < requestedTileHeight; y++) {
		for (int x = 0; x < requestedTileWidth; x++) {

			double longitude = requestBoundingBox.getMinLongitude()
					+ (x * requestedWidthUnitsPerPixel);
			double latitude = requestBoundingBox.getMaxLatitude()
					- (y * requestedHeightUnitsPerPixel);
			ProjCoordinate fromCoord = new ProjCoordinate(longitude,
					latitude);
			ProjCoordinate toCoord = transformRequestToTiles
					.transform(fromCoord);
			double projectedLongitude = toCoord.x;
			double projectedLatitude = toCoord.y;

			int xPixel = (int) Math
					.round(((projectedLongitude - tilesBoundingBox
							.getMinLongitude()) / tilesDistanceWidth)
							* width);
			int yPixel = (int) Math
					.round(((tilesBoundingBox.getMaxLatitude() - projectedLatitude) / tilesDistanceHeight)
							* height);

			xPixel = Math.max(0, xPixel);
			xPixel = Math.min(width - 1, xPixel);

			yPixel = Math.max(0, yPixel);
			yPixel = Math.min(height - 1, yPixel);

			int color = pixels[(yPixel * width) + xPixel];
			projectedPixels[(y * requestedTileWidth) + x] = color;
		}
	}

	// Draw the new image
	BufferedImage projectedTileImage = new BufferedImage(
			requestedTileWidth, requestedTileHeight, tile.getType());
	projectedTileImage.setRGB(0, 0, requestedTileWidth,
			requestedTileHeight, projectedPixels, 0, requestedTileWidth);

	return projectedTileImage;
}
 
Example 17
Source Project: mzmine3   File: TwoDXYPlot.java    License: GNU General Public License v2.0 4 votes vote down vote up
public boolean render(final Graphics2D g2, final Rectangle2D dataArea, int index,
    PlotRenderingInfo info, CrosshairState crosshairState) {

  // if this is not TwoDDataSet
  if (index != 0)
    return super.render(g2, dataArea, index, info, crosshairState);

  // prepare some necessary constants
  final int x = (int) dataArea.getX();
  final int y = (int) dataArea.getY();
  final int width = (int) dataArea.getWidth();
  final int height = (int) dataArea.getHeight();

  final double imageRTMin = (double) getDomainAxis().getRange().getLowerBound();
  final double imageRTMax = (double) getDomainAxis().getRange().getUpperBound();
  final double imageRTStep = (imageRTMax - imageRTMin) / width;
  final double imageMZMin = (double) getRangeAxis().getRange().getLowerBound();
  final double imageMZMax = (double) getRangeAxis().getRange().getUpperBound();
  final double imageMZStep = (imageMZMax - imageMZMin) / height;

  if ((zoomOutBitmap != null) && (imageRTMin == totalRTRange.lowerEndpoint())
      && (imageRTMax == totalRTRange.upperEndpoint())
      && (imageMZMin == totalMZRange.lowerEndpoint())
      && (imageMZMax == totalMZRange.upperEndpoint()) && (zoomOutBitmap.getWidth() == width)
      && (zoomOutBitmap.getHeight() == height)) {
    g2.drawImage(zoomOutBitmap, x, y, null);
    return true;
  }

  // Save current time
  Date renderStartTime = new Date();

  // prepare a double array of summed intensities
  double values[][] = new double[width][height];
  maxValue = 0; // now this is an instance variable

  for (int i = 0; i < width; i++)
    for (int j = 0; j < height; j++) {

      double pointRTMin = imageRTMin + (i * imageRTStep);
      double pointRTMax = pointRTMin + imageRTStep;
      double pointMZMin = imageMZMin + (j * imageMZStep);
      double pointMZMax = pointMZMin + imageMZStep;

      double lv = dataset.upperEndpointIntensity(Range.closed(pointRTMin, pointRTMax),
          Range.closed(pointMZMin, pointMZMax), plotMode);

      if (logScale) {
        lv = Math.log10(lv);
        if (lv < 0 || Double.isInfinite(lv))
          lv = 0;
        values[i][j] = lv;
        // values[r.nextInt(width)][r.nextInt(height)] = lv;
      } else {
        values[i][j] = lv;
      }

      if (lv > maxValue)
        maxValue = lv;

    }

  // This should never happen, but just for correctness
  if (maxValue == 0)
    return false;

  // Normalize all values
  for (int i = 0; i < width; i++)
    for (int j = 0; j < height; j++) {
      values[i][j] /= maxValue;
    }

  // prepare a bitmap of required size
  BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

  // draw image points
  for (int i = 0; i < width; i++)
    for (int j = 0; j < height; j++) {
      Color pointColor = paletteType.getColor(values[i][j]);
      image.setRGB(i, height - j - 1, pointColor.getRGB());
    }

  // if we are zoomed out, save the values
  if ((imageRTMin == totalRTRange.lowerEndpoint()) && (imageRTMax == totalRTRange.upperEndpoint())
      && (imageMZMin == totalMZRange.lowerEndpoint())
      && (imageMZMax == totalMZRange.upperEndpoint())) {
    zoomOutBitmap = image;
  }

  // Paint image
  g2.drawImage(image, x, y, null);

  Date renderFinishTime = new Date();

  logger.finest("Finished rendering 2D visualizer, "
      + (renderFinishTime.getTime() - renderStartTime.getTime()) + " ms");

  return true;

}
 
Example 18
Source Project: MyBox   File: ImageManufacture.java    License: Apache License 2.0 4 votes vote down vote up
public static BufferedImage blurMarginsNoAlpha(BufferedImage source,
        int blurWidth,
        boolean blurTop, boolean blurBottom, boolean blurLeft,
        boolean blurRight) {
    try {
        int width = source.getWidth();
        int height = source.getHeight();
        int imageType = BufferedImage.TYPE_INT_RGB;
        BufferedImage target = new BufferedImage(width, height, imageType);
        float iOpocity, jOpacity, opocity;
        Color alphaColor = ImageColor.getAlphaColor();
        for (int j = 0; j < height; ++j) {
            for (int i = 0; i < width; ++i) {
                int pixel = source.getRGB(i, j);
                if (pixel == 0) {
                    target.setRGB(i, j, alphaColor.getRGB());
                    continue;
                }
                iOpocity = jOpacity = 1.0f;
                if (i < blurWidth) {
                    if (blurLeft) {
                        iOpocity = 1.0f * i / blurWidth;
                    }
                } else if (i > width - blurWidth) {
                    if (blurRight) {
                        iOpocity = 1.0f * (width - i) / blurWidth;
                    }
                }
                if (j < blurWidth) {
                    if (blurTop) {
                        jOpacity = 1.0f * j / blurWidth;
                    }
                } else if (j > height - blurWidth) {
                    if (blurBottom) {
                        jOpacity = 1.0f * (height - j) / blurWidth;
                    }
                }
                opocity = iOpocity * jOpacity;
                if (opocity == 1.0f) {
                    target.setRGB(i, j, pixel);
                } else {
                    Color color = ImageColor.blendAlpha(new Color(pixel), opocity, alphaColor);
                    target.setRGB(i, j, color.getRGB());
                }
            }
        }
        return target;
    } catch (Exception e) {
        logger.error(e.toString());
        return null;
    }
}
 
Example 19
Source Project: hottub   File: PixelTests.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void runTest(Object context, int numReps) {
    BufferedImage bimg = ((Context) context).bimg;
    do {
        bimg.setRGB(numReps&7, 0, BufImg.rgbvals[numReps&3]);
    } while (--numReps > 0);
}
 
Example 20
private static Image getStandardViewButton(int iconIndex) {
    Image result = STANDARD_VIEW_BUTTONS[iconIndex];

    if (result != null) {
        return result;
    }

    BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);

    img.setRGB(0, 0, 16, 16, Win32ShellFolder2.getStandardViewButton0(iconIndex), 0, 16);

    STANDARD_VIEW_BUTTONS[iconIndex] = img;

    return img;
}