java.awt.image.BufferedImage#setRGB()源码实例Demo

下面列出了java.awt.image.BufferedImage#setRGB() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-8-source   文件: EffectUtils.java
/**
 * <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);
    }
}
 
源代码2 项目: springboot-pay-example   文件: PayUtil.java
/**
 * 根据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;
}
 
源代码3 项目: pyramid   文件: KMeansTest.java
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));
    }
 
源代码4 项目: AILibs   文件: DataSetUtils.java
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);
}
 
源代码5 项目: pdfbox-layout   文件: ExampleTest.java
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;
   }
 
源代码6 项目: filthy-rich-clients   文件: GraphicsUtilities.java
/**
 * <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);
    }
}
 
源代码7 项目: TGAReader   文件: TGASwingBufferedImage.java
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);
}
 
源代码8 项目: mars-sim   文件: GraphicsUtilities.java
/**
 * <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);
    }
}
 
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;
}
 
源代码10 项目: mapwriter   文件: MergeToImage.java
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;
}
 
@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);
}
 
源代码12 项目: jdk8u60   文件: Win32ShellFolder2.java
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;
}
 
源代码13 项目: Pixie   文件: Utils.java
/**
 * 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;
}
 
源代码14 项目: Lottery   文件: AverageImageScale.java
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;
}
 
源代码15 项目: common-project   文件: QRCodeUtil.java
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;
}
 
源代码16 项目: geopackage-java   文件: TileCreator.java
/**
 * 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;
}
 
源代码17 项目: mzmine3   文件: TwoDXYPlot.java
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;

}
 
源代码18 项目: MyBox   文件: ImageManufacture.java
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;
    }
}
 
源代码19 项目: hottub   文件: PixelTests.java
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);
}
 
源代码20 项目: dragonwell8_jdk   文件: Win32ShellFolderManager2.java
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;
}