Java Code Examples for java.awt.image.BufferedImage#TYPE_4BYTE_ABGR

The following examples show how to use java.awt.image.BufferedImage#TYPE_4BYTE_ABGR . 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
Source File: OpCompatibleImageTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private static String describeType(int type) {
    switch(type) {
    case BufferedImage.TYPE_3BYTE_BGR:
        return "TYPE_3BYTE_BGR";
    case BufferedImage.TYPE_4BYTE_ABGR:
        return "TYPE_4BYTE_ABGR";
    case BufferedImage.TYPE_BYTE_GRAY:
        return "TYPE_BYTE_GRAY";
    case BufferedImage.TYPE_INT_ARGB:
        return "TYPE_INT_ARGB";
    case BufferedImage.TYPE_INT_BGR:
        return  "TYPE_INT_BGR";
    case BufferedImage.TYPE_INT_RGB:
        return "TYPE_INT_RGB";
    case BufferedImage.TYPE_BYTE_INDEXED:
        return "TYPE_BYTE_INDEXED";
    default:
        throw new RuntimeException("Test FAILED: unknown type " + type);
    }
}
 
Example 2
Source File: ImageLoader.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
protected BufferedImage scalingIfNeed(BufferedImage image, long dstHeight, long dstWidth, long dstImageType, boolean needAlpha) {
    Image scaled;
    // Scale width and height first if necessary
    if (dstHeight > 0 && dstWidth > 0 && (image.getHeight() != dstHeight || image.getWidth() != dstWidth)) {
        scaled = image.getScaledInstance((int) dstWidth, (int) dstHeight, Image.SCALE_SMOOTH);
    } else {
        scaled = image;
    }

    // Transfer imageType if necessary and transfer to BufferedImage.
    if (scaled instanceof BufferedImage && ((BufferedImage) scaled).getType() == dstImageType) {
        return (BufferedImage) scaled;
    }
    if (needAlpha && image.getColorModel().hasAlpha() && dstImageType == BufferedImage.TYPE_4BYTE_ABGR) {
        return toBufferedImage(scaled, BufferedImage.TYPE_4BYTE_ABGR);
    } else {
        if (dstImageType == BufferedImage.TYPE_BYTE_GRAY)
            return toBufferedImage(scaled, BufferedImage.TYPE_BYTE_GRAY);
        else
            return toBufferedImage(scaled, BufferedImage.TYPE_3BYTE_BGR);
    }
}
 
Example 3
Source File: RenderedImageIconTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testPaint() throws IOException {
	BufferedImage img = ImageIO.read(getClass().getResourceAsStream(
			"/org/geomajas/plugin/rasterizing/images/testIcon.png"));
	RenderedImageIcon icon = new RenderedImageIcon(img, 24, 24);

	BufferedImage copy = new BufferedImage(24, 24, BufferedImage.TYPE_4BYTE_ABGR);
	icon.paintIcon(null, copy.getGraphics(), 0, 0);
	copy.getGraphics().dispose();

	//ImageIO.write(copy, "png", new FileOutputStream("my.png"));
	
	Raster r1 = img.getData();
	Raster r2 = copy.getData();
	for (int i = 0; i < 24; i++) {
		for (int j = 0; j < 24; j++) {
			int[] p1 = r1.getPixel(i, j, (int[]) null);
			int[] p2 = r2.getPixel(i, j, (int[]) null);
			Assert.assertArrayEquals(p2, p1);
		}
	}

}
 
Example 4
Source File: LWJGLTextDrawer.java    From settlers-remake with MIT License 6 votes vote down vote up
/**
 * Creates a new text drawer.
 *
 */
public LWJGLTextDrawer(LWJGL15DrawContext drawContext) {
	this.drawContext = drawContext;
	font = new Font(FONTNAME, Font.PLAIN, TEXTURE_GENERATION_SIZE);

	BufferedImage tmp_bi = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
	Graphics tmp_graph = tmp_bi.getGraphics();
	tmp_graph.setFont(font);
	FontMetrics fm = tmp_graph.getFontMetrics();
	char_widths = fm.getWidths();
	gentex_line_height = fm.getHeight();
	tmp_graph.dispose();

	if(char_widths.length != 256) {
		throw new IndexOutOfBoundsException("we only support 256 characters (256!="+char_widths.length);
	}

	generateTexture();
	generateGeometry(fm.getDescent());
}
 
Example 5
Source File: Utils.java    From Pixie with MIT License 6 votes vote down vote up
/**
 * Copy one buffered image to another.
 *
 * @param src - source image
 * @param dst - destination image
 */
public static void copySrcIntoDstAt(final BufferedImage src, final BufferedImage dst) {
    byte[] srcBuf = getByteData(src);
    byte[] dstBuf = getByteData(dst);
    int representationFactor;

    // width * hight * 3 because of rgb components and byte representation
    switch (src.getType()) {
        case BufferedImage.TYPE_BYTE_GRAY:
        case BufferedImage.TYPE_BYTE_INDEXED:
            representationFactor = 1;
            break;
        case BufferedImage.TYPE_3BYTE_BGR:
            representationFactor = 3;
            break;
        case BufferedImage.TYPE_4BYTE_ABGR:
            representationFactor = 4;
            break;
        default:
            representationFactor = 3;
            break;
    }

    System.arraycopy(srcBuf, 0, dstBuf, 0, src.getWidth() * src.getHeight() * representationFactor);
}
 
Example 6
Source File: OpCompatibleImageTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static String describeType(int type) {
    switch(type) {
    case BufferedImage.TYPE_3BYTE_BGR:
        return "TYPE_3BYTE_BGR";
    case BufferedImage.TYPE_4BYTE_ABGR:
        return "TYPE_4BYTE_ABGR";
    case BufferedImage.TYPE_BYTE_GRAY:
        return "TYPE_BYTE_GRAY";
    case BufferedImage.TYPE_INT_ARGB:
        return "TYPE_INT_ARGB";
    case BufferedImage.TYPE_INT_BGR:
        return  "TYPE_INT_BGR";
    case BufferedImage.TYPE_INT_RGB:
        return "TYPE_INT_RGB";
    case BufferedImage.TYPE_BYTE_INDEXED:
        return "TYPE_BYTE_INDEXED";
    default:
        throw new RuntimeException("Test FAILED: unknown type " + type);
    }
}
 
Example 7
Source File: BigImagePanelTest.java    From Open-Realms-of-Stars with GNU General Public License v2.0 5 votes vote down vote up
@Test
@Category(org.openRealmOfStars.BehaviourTest.class)
public void testDrawingWithTitle() {
  BufferedImage image = new BufferedImage(1024, 768, BufferedImage.TYPE_4BYTE_ABGR);
  BigImagePanel panel = new BigImagePanel(null, true, "Planet view");
  panel.setTitle("Example title");
  panel.paint(image.getGraphics());
}
 
Example 8
Source File: Screenshots.java    From depan with Apache License 2.0 5 votes vote down vote up
/**
 * Stolen from com.jogamp.opengl.util.awt.Screenshot.readToBufferedImage()
 * 
 * JOGL 2.1.2
 */
private static BufferedImage readToBufferedImage(
    int x,int y, int width, int height, boolean alpha) throws GLException {

  int bufImgType = (alpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR);
  int readbackType = (alpha ? GL2.GL_ABGR_EXT : GL2ES3.GL_BGR);

  // Allocate necessary storage
  BufferedImage image = new BufferedImage(width, height, bufImgType);

  GLContext glc = GLContext.getCurrent();
  GL gl = glc.getGL();

  // Set up pixel storage modes
  GLPixelStorageModes psm = new GLPixelStorageModes();
  psm.setPackAlignment(gl, 1);

  // read the BGR values into the image
  gl.glReadPixels(x, y, width, height, readbackType,
      GL.GL_UNSIGNED_BYTE,
      ByteBuffer.wrap(((DataBufferByte) image.getRaster().getDataBuffer()).getData()));

  // Restore pixel storage modes
  psm.restore(gl);

  if( glc.getGLDrawable().isGLOriented() ) {
    // Must flip BufferedImage vertically for correct results
    ImageUtil.flipImageVertically(image);
  }
  return image;
}
 
Example 9
Source File: MCRThumbnailUtils.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static int getImageType(BufferedImage image) {
    int colorType = 12;
    for (int x = 0; x < image.getWidth(); x++) {
        for (int y = 0; y < image.getHeight(); y++) {
            int colorTypeTemp = getColorType(image.getRGB(x, y));
            if (colorTypeTemp == BufferedImage.TYPE_4BYTE_ABGR) {
                return BufferedImage.TYPE_4BYTE_ABGR;
            }
            colorType = colorTypeTemp < colorType ? colorTypeTemp : colorType;
        }
    }
    return colorType;
}
 
Example 10
Source File: GeometryDirectLayerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
public void generateActual(OutputStream out) throws Exception {
	Rectangle rect = mapContext.getViewport().getScreenArea();
	BufferedImage image = new BufferedImage((int) rect.getWidth(), (int) rect.getHeight(),
			BufferedImage.TYPE_4BYTE_ABGR);
	layer.draw(image.createGraphics(), mapContext, mapContext.getViewport());
	ImageIO.write(image, "PNG", out);
}
 
Example 11
Source File: ColConvTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static String getImageTypeName(int type) {
    switch(type) {
        case BufferedImage.TYPE_INT_ARGB:
            return "TYPE_INT_ARGB";
        case BufferedImage.TYPE_INT_RGB:
            return "TYPE_INT_RGB";
        case BufferedImage.TYPE_INT_BGR:
            return "TYPE_INT_BGR";
        case BufferedImage.TYPE_INT_ARGB_PRE:
            return "TYPE_INT_ARGB_PRE";
        case BufferedImage.TYPE_3BYTE_BGR:
            return "TYPE_3BYTE_BGR";
        case BufferedImage.TYPE_4BYTE_ABGR:
            return "TYPE_4BYTE_ABGR";
        case BufferedImage.TYPE_4BYTE_ABGR_PRE:
            return "TYPE_4BYTE_ABGR_PRE";
        case BufferedImage.TYPE_BYTE_BINARY:
            return "TYPE_BYTE_BINARY";
        case BufferedImage.TYPE_BYTE_GRAY:
            return "TYPE_BYTE_GRAY";
        case BufferedImage.TYPE_BYTE_INDEXED:
            return "TYPE_BYTE_INDEXED";
        case BufferedImage.TYPE_USHORT_555_RGB:
            return "TYPE_USHORT_555_RGB";
        case BufferedImage.TYPE_USHORT_565_RGB:
            return "TYPE_USHORT_565_RGB";
        case BufferedImage.TYPE_USHORT_GRAY:
            return "TYPE_USHORT_GRAY";
    }
    return "UNKNOWN";
}
 
Example 12
Source File: SvgImporter.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
private static void svgTest(String name) throws IOException, InterruptedException {
    if (!new File(name + ".original.svg").exists()) {
        URL svgUrl = new URL("http://www.w3.org/Graphics/SVG/Test/20061213/svggen/" + name + ".svg");
        byte[] svgData = Helper.readStream(svgUrl.openStream());
        Helper.writeFile(name + ".orig.svg", svgData);

        URL pngUrl = new URL("http://www.w3.org/Graphics/SVG/Test/20061213/png/full-" + name + ".png");
        byte[] pngData = Helper.readStream(pngUrl.openStream());
        Helper.writeFile(name + ".orig.png", pngData);
    }

    String svgDataS = Helper.readTextFile(name + ".orig.svg");
    SWF swf = new SWF();
    DefineShape4Tag st = new DefineShape4Tag(swf);
    st = (DefineShape4Tag) (new SvgImporter().importSvg(st, svgDataS));
    swf.addTag(st);
    SerializableImage si = new SerializableImage(480, 360, BufferedImage.TYPE_4BYTE_ABGR);
    BitmapExporter.export(swf, st.shapes, Color.yellow, si, new Matrix(), new Matrix(), null);
    List<Tag> li = new ArrayList<>();
    li.add(st);
    ImageIO.write(si.getBufferedImage(), "PNG", new File(name + ".imported.png"));
    ExportAssetsTag eat = new ExportAssetsTag(swf);
    eat.tags.add(st.getCharacterId());
    eat.names.add(name);
    swf.addTag(eat);
    swf.assignExportNamesToSymbols();
    st.shapeBounds.Xmax = (int) (si.getWidth() * SWF.unitDivisor);
    st.shapeBounds.Ymax = (int) (si.getHeight() * SWF.unitDivisor);
    new ShapeExporter().exportShapes(null, "./outex/", swf, new ReadOnlyTagList(li), new ShapeExportSettings(ShapeExportMode.SVG, 1), null);
}
 
Example 13
Source File: RasterDirectLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Converts an image to a RGBA direct color model using a workaround via buffered image directly calling the
 * ColorConvert operation fails for unknown reasons ?!
 *
 * @param img image to convert
 * @return converted image
 */
public PlanarImage toDirectColorModel(RenderedImage img) {
	BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
	BufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(), img
			.getColorModel().isAlphaPremultiplied(), null);
	ColorConvertOp op = new ColorConvertOp(null);
	op.filter(source, dest);
	return PlanarImage.wrapRenderedImage(dest);
}
 
Example 14
Source File: ImageTailor.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
/**
 * Do processing cut image.
 * 
 * @param sourceImg
 * @return
 * @throws IOException
 */
private TailoredImage doProcess(BufferedImage sourceImg) throws IOException {
	int width = sourceImg.getWidth();
	int height = sourceImg.getHeight();
	// Check maximum effective width height
	isTrue((width <= sourceMaxWidth && height <= sourceMaxHeight),
			String.format("Source image is too big, max limits: %d*%d", sourceMaxWidth, sourceMaxHeight));
	isTrue((width >= sourceMinWidth && height >= sourceMinHeight),
			String.format("Source image is too small, min limits: %d*%d", sourceMinWidth, sourceMinHeight));

	// 创建背景图,TYPE_4BYTE_ABGR表示具有8位RGBA颜色分量的图像(支持透明的BufferedImage),正常取bufImg.getType()
	BufferedImage primaryImg = new BufferedImage(sourceImg.getWidth(), sourceImg.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
	// 创建滑块图
	BufferedImage blockImg = new BufferedImage(sourceImg.getWidth(), sourceImg.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
	// 随机截取的坐标
	int maxX0 = width - blockWidth - (circleR + circleOffset);
	int maxY0 = height - blockHeight;
	int blockX0 = current().nextInt((int) (maxX0 * 0.25), maxX0); // *0.25防止x坐标太靠左
	int blockY0 = current().nextInt(circleR, maxY0); // 从circleR开始是为了防止上边的耳朵显示不全
	// Setup block borders position.
	initBorderPositions(blockX0, blockY0, blockWidth, blockHeight);

	// 绘制生成新图(图片大小是固定,位置是随机)
	drawing(sourceImg, blockImg, primaryImg, blockX0, blockY0, blockWidth, blockHeight);
	// 裁剪可用区
	int cutX0 = blockX0;
	int cutY0 = Math.max((blockY0 - circleR - circleOffset), 0);
	int cutWidth = blockWidth + circleR + circleOffset;
	int cutHeight = blockHeight + circleR + circleOffset;
	blockImg = blockImg.getSubimage(cutX0, cutY0, cutWidth, cutHeight);

	// Add watermark string.
	addWatermarkIfNecessary(primaryImg);

	// 输出图像数据
	TailoredImage img = new TailoredImage();
	// Primary image.
	ByteArrayOutputStream primaryData = new ByteArrayOutputStream();
	ImageIO.write(primaryImg, "PNG", primaryData);
	img.setPrimaryImg(primaryData.toByteArray());

	// Block image.
	ByteArrayOutputStream blockData = new ByteArrayOutputStream();
	ImageIO.write(blockImg, "PNG", blockData);
	img.setBlockImg(blockData.toByteArray());

	// Position
	img.setX(blockX0);
	img.setY(blockY0 - circleR >= 0 ? blockY0 - circleR : 0);
	return img;
}
 
Example 15
Source File: PixelTests.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void init() {
    pixelroot = new Group("pixel", "Pixel Access Benchmarks");

    pixeloptroot = new Group(pixelroot, "opts", "Pixel Access Options");
    doRenderTo = new Option.Toggle(pixeloptroot, "renderto",
                                   "Render to Image before test",
                                   Option.Toggle.Off);
    doRenderFrom = new Option.Toggle(pixeloptroot, "renderfrom",
                                     "Render from Image before test",
                                     Option.Toggle.Off);

    // BufferedImage Sources
    bufimgsrcroot = new Group.EnableSet(pixelroot, "src",
                                        "BufferedImage Sources");
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 1);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 2);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 4);
    new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
    new BufImg(BufferedImage.TYPE_BYTE_GRAY);
    new BufImg(BufferedImage.TYPE_USHORT_555_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_565_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_GRAY);
    new BufImg(BufferedImage.TYPE_3BYTE_BGR);
    new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
    new BufImg(BufferedImage.TYPE_INT_RGB);
    new BufImg(BufferedImage.TYPE_INT_BGR);
    new BufImg(BufferedImage.TYPE_INT_ARGB);

    // BufferedImage Tests
    bufimgtestroot = new Group(pixelroot, "bimgtests",
                               "BufferedImage Tests");
    new BufImgTest.GetRGB();
    new BufImgTest.SetRGB();

    // Raster Tests
    rastertestroot = new Group(pixelroot, "rastests",
                               "Raster Tests");
    new RasTest.GetDataElements();
    new RasTest.SetDataElements();
    new RasTest.GetPixel();
    new RasTest.SetPixel();

    // DataBuffer Tests
    dbtestroot = new Group(pixelroot, "dbtests",
                           "DataBuffer Tests");
    new DataBufTest.GetElem();
    new DataBufTest.SetElem();
}
 
Example 16
Source File: IntegerMapData.java    From mars-sim with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Image getMapImage(double centerPhi, double centerTheta) {

	// Create a new buffered image to draw the map on.
	BufferedImage result = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);//BufferedImage.TYPE_INT_ARGB);

	// The map data is PI offset from the center theta.
	double correctedTheta = centerTheta - Math.PI;
	while (correctedTheta < 0D)
		correctedTheta += TWO_PI;
	while (correctedTheta > TWO_PI)
		correctedTheta -= TWO_PI;

	// Create an array of int RGB color values to create the map image from.
	int[] mapArray = new int[IMAGE_WIDTH * IMAGE_HEIGHT];

	// Determine phi iteration angle.
	double phiIterationPadding = 1.26D; // Derived from testing.
	double phiIterationAngle = Math.PI / (MAP_HEIGHT / MAP_RATIO * phiIterationPadding);

	// Determine phi range.
	double phiPadding = 1.46D; // Derived from testing.
	double phiRange = Math.PI * phiPadding * IMAGE_HEIGHT / MAP_HEIGHT * MAP_RATIO;

	// Determine starting and ending phi values.
	double startPhi = centerPhi - (phiRange / 2D);
	if (startPhi < 0D)
		startPhi = 0D;
	double endPhi = centerPhi + (phiRange / 2D);
	if (endPhi > Math.PI)
		endPhi = Math.PI;

	double ratio = TWO_PI * IMAGE_WIDTH / MAP_WIDTH * MAP_RATIO;
	// Note : Polar cap phi values must display 2 PI theta range. 
	// (derived from testing)
	double polarCapRange = Math.PI / 6.54D; 
	// Determine theta iteration angle.
	double thetaIterationPadding = 1.46D; // Derived from testing.
	// Theta padding, derived from testing.
	double minThetaPadding = 1.02D; 
	// Determine theta range.
	double minThetaDisplay = ratio * minThetaPadding;
	
	// Loop through each phi value.
	for (double x = startPhi; x <= endPhi; x += phiIterationAngle) {

		double thetaIterationAngle = TWO_PI / (((double) MAP_WIDTH / MAP_RATIO * Math.sin(x) * thetaIterationPadding) + 1D);

		double thetaRange = ((1D - Math.sin(x)) * TWO_PI) + minThetaDisplay;
		
		if ((x < polarCapRange) || (x > (Math.PI - polarCapRange)))
			thetaRange = TWO_PI;
		if (thetaRange > TWO_PI)
			thetaRange = TWO_PI;

		// Determine the theta starting and ending values.
		double startTheta = centerTheta - (thetaRange / 2D);
		double endTheta = centerTheta + (thetaRange / 2D);

		// Loop through each theta value.
		for (double y = startTheta; y <= endTheta; y += thetaIterationAngle) {

			// Correct y value to make sure it is within bounds. (0 to 2PI)
			double yCorrected = y;
			while (yCorrected < 0)
				yCorrected += TWO_PI;
			while (yCorrected > TWO_PI)
				yCorrected -= TWO_PI;

			// Determine the rectangular offset of the pixel in the image.
			Point location = findRectPosition(centerPhi, centerTheta, x, yCorrected, 1440D / Math.PI, 720,
					720 - 150);

			// Determine the display x and y coordinates for the pixel in the image.
			int displayX = IMAGE_WIDTH - location.x;
			int displayY = IMAGE_HEIGHT - location.y;

			// Check that the x and y coordinates are within the display area.
			boolean leftBounds = displayX >= 0;
			boolean rightBounds = displayX < IMAGE_WIDTH;
			boolean topBounds = displayY >= 0;
			boolean bottomBounds = displayY < IMAGE_HEIGHT;
			if (leftBounds && rightBounds && topBounds && bottomBounds) {

				// Determine array index for the display location.
				int index = (IMAGE_WIDTH - displayX) + ((IMAGE_HEIGHT - displayY) * IMAGE_WIDTH);

				// Put color in array at index.
				if ((index >= 0) && (index < mapArray.length))
					mapArray[index] = getRGBColorInt(x, yCorrected);
			}
		}
	}

	// Create new map image.
	result.setRGB(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, mapArray, 0, IMAGE_WIDTH);

	return result;
}
 
Example 17
Source File: RotateWordTest.java    From kumo with MIT License 4 votes vote down vote up
@Ignore
public void checkRotatedTextIsNotCropped() throws IOException {
    BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D graphics = image.createGraphics();

    // set the rendering hint here to ensure the font metrics are correct
    graphics.setRenderingHints(Word.getRenderingHints());
    FontMetrics fontMetrics = graphics.getFontMetrics(_font);

    for (int angle = 0; angle < 360; angle += 5) {
        Word word = new Word(
                _text, Color.red, fontMetrics, null, Math.toRadians(angle)
        );

        BufferedImage rendered = word.getBufferedImage();

        int width = rendered.getWidth();
        int height = rendered.getHeight();

        try {
            for (int y = 0; y < height; y++) {
                Assert.assertTrue(
                        "text doesn't touch the outer left line",
                        nearlyTransparent(rendered.getRGB(0, y))
                );
                Assert.assertTrue(
                        "text doesn't touch the outer right line",
                        nearlyTransparent(rendered.getRGB(width - 1, y))
                );
            }

            for (int x = 0; x < width; x++) {
                Assert.assertTrue(
                        "text doesn't touch the top line",
                        nearlyTransparent(rendered.getRGB(x, 0))
                );
                Assert.assertTrue(
                        "text doesn't touch the bottom line",
                        nearlyTransparent(rendered.getRGB(x, height - 1))
                );
            }
        } catch (AssertionError e) {
            File file = new File("output/FailedRotateWordTest_" + System.currentTimeMillis() + ".png");
            ImageIO.write(rendered, "png", file);

            throw e;
        }
    }
}
 
Example 18
Source File: NewsCorpView.java    From Open-Realms-of-Stars with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Construtor for News Corp View.
 * @param news News Data
 * @param listener ActionListener
 */
public NewsCorpView(final NewsData[] news, final ActionListener listener) {
  this.setLayout(new BorderLayout());
  newsList = news;
  InfoPanel base = new InfoPanel();
  boolean musicChanged = false;
  if (news[0].getNewsText().contains("Today is sad day for ")
      || news[0].getNewsText().contains("was killed in battle!")) {
    MusicPlayer.play(MusicPlayer.DEATH_IS_JUST_ANOTHER_PATH);
    musicChanged = true;
  }
  if (!musicChanged
      && MusicPlayer.getNowPlaying() != MusicPlayer.SPACE_THEME) {
    MusicPlayer.play(MusicPlayer.SPACE_THEME);
  }
  base.setLayout(new BorderLayout());
  base.setTitle("Galactic Broadcasting News Company");
  newsReaderPanel = new ImagePanel(GuiStatics.IMAGE_SCAURIAN_RACE);
  int heightNewsReader = 700;
  widthHeadLine = 800;
  heightHeadLine = 400;
  if (listener instanceof Game) {
    Game game = (Game) listener;
    heightNewsReader = game.getHeight() - 50;
    widthHeadLine = game.getWidth() - 220;
  }
  newsReader = new BufferedImage(196, heightNewsReader,
      BufferedImage.TYPE_4BYTE_ABGR);
  animation = 0;
  newsReaderPanel.setImage(newsReader);
  base.add(newsReaderPanel, BorderLayout.WEST);
  InfoPanel newsPanel = new InfoPanel();
  newsPanel.setLayout(new BoxLayout(newsPanel, BoxLayout.Y_AXIS));
  newsPanel.setTitle("News headline");
  BufferedImage image = new BufferedImage(widthHeadLine, heightHeadLine,
      BufferedImage.TYPE_4BYTE_ABGR);
  image = ImageInstruction.parseImageInstructions(image,
      news[0].getImageInstructions());
  newsImage = new ImagePanel(image);
  newsPanel.add(newsImage, BorderLayout.WEST);
  newsPanel.add(Box.createRigidArea(new Dimension(15, 10)));
  textArea = new InfoTextArea();
  textArea.setCharacterWidth(9);
  textArea.setText(news[0].getNewsText());
  textArea.setLineWrap(true);
  textArea.setEditable(false);
  newsPanel.add(textArea);
  this.add(base, BorderLayout.CENTER);
  SpaceGreyPanel panel = new SpaceGreyPanel();
  panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
  IconButton iBtn = new IconButton(GuiStatics.LEFT_ARROW,
      GuiStatics.LEFT_ARROW_PRESSED, false, GameCommands.COMMAND_PREV_TARGET,
      this);
  iBtn.addActionListener(listener);
  panel.add(iBtn);
  panel.add(Box.createRigidArea(new Dimension(10, 5)));
  newsLabel = new SpaceLabel("100/100");
  newsLabel.setText("1/" + newsList.length);
  panel.add(newsLabel);
  iBtn = new IconButton(GuiStatics.RIGHT_ARROW,
      GuiStatics.RIGHT_ARROW_PRESSED, false, GameCommands.COMMAND_NEXT_TARGET,
      this);
  iBtn.addActionListener(listener);
  panel.add(iBtn);
  newsPanel.add(Box.createRigidArea(new Dimension(5, 5)));
  newsPanel.add(panel);
  base.add(newsPanel, BorderLayout.CENTER);
  // Bottom panel
  InfoPanel bottomPanel = new InfoPanel();
  bottomPanel.setLayout(new BorderLayout());
  bottomPanel.setTitle(null);
  SpaceButton btn = new SpaceButton("Back to star map",
      GameCommands.COMMAND_VIEW_STARMAP);
  btn.addActionListener(listener);
  bottomPanel.add(btn, BorderLayout.CENTER);
  // Add panels to base
  this.add(bottomPanel, BorderLayout.SOUTH);
}
 
Example 19
Source File: PixelTests.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void init() {
    pixelroot = new Group("pixel", "Pixel Access Benchmarks");

    pixeloptroot = new Group(pixelroot, "opts", "Pixel Access Options");
    doRenderTo = new Option.Toggle(pixeloptroot, "renderto",
                                   "Render to Image before test",
                                   Option.Toggle.Off);
    doRenderFrom = new Option.Toggle(pixeloptroot, "renderfrom",
                                     "Render from Image before test",
                                     Option.Toggle.Off);

    // BufferedImage Sources
    bufimgsrcroot = new Group.EnableSet(pixelroot, "src",
                                        "BufferedImage Sources");
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 1);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 2);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 4);
    new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
    new BufImg(BufferedImage.TYPE_BYTE_GRAY);
    new BufImg(BufferedImage.TYPE_USHORT_555_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_565_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_GRAY);
    new BufImg(BufferedImage.TYPE_3BYTE_BGR);
    new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
    new BufImg(BufferedImage.TYPE_INT_RGB);
    new BufImg(BufferedImage.TYPE_INT_BGR);
    new BufImg(BufferedImage.TYPE_INT_ARGB);

    // BufferedImage Tests
    bufimgtestroot = new Group(pixelroot, "bimgtests",
                               "BufferedImage Tests");
    new BufImgTest.GetRGB();
    new BufImgTest.SetRGB();

    // Raster Tests
    rastertestroot = new Group(pixelroot, "rastests",
                               "Raster Tests");
    new RasTest.GetDataElements();
    new RasTest.SetDataElements();
    new RasTest.GetPixel();
    new RasTest.SetPixel();

    // DataBuffer Tests
    dbtestroot = new Group(pixelroot, "dbtests",
                           "DataBuffer Tests");
    new DataBufTest.GetElem();
    new DataBufTest.SetElem();
}
 
Example 20
Source File: CodeUtil.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *生成带logo的二维码图片
 * @param logoFile /logo图片文件
 * @param codeFile /二维码图片
 * @param qrUrl /二维码存储的信息:vcard格式
 * @param note /二维码描述信息
 */
public static byte[] drawLogoQRCodeByte(BufferedImage logo, ByteArrayOutputStream codeFile, String qrUrl, String note) {
	byte[] bs = null;
    try {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
        BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

        // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
        for (int x = 0; x < WIDTH; x++) {
            for (int y = 0; y < HEIGHT; y++) {
                image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
            }
        }

        int width = image.getWidth();
        int height = image.getHeight();
        if (Objects.nonNull(logo)) {
            // 构建绘图对象
            Graphics2D g = image.createGraphics();
            // 读取Logo图片
            //BufferedImage logo = ImageIO.read(logoFile);
            // 开始绘制logo图片
            g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
            g.dispose();
            logo.flush();
        }

        // 自定义文本描述
        if (StringUtils.isNotEmpty(note)) {
            // 新的图片,把带logo的二维码下面加上文字
            BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D outg = outImage.createGraphics();
            // 画二维码到新的面板
            outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            outg.setColor(Color.BLACK);
            outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
            int strWidth = outg.getFontMetrics().stringWidth(note);
            if (strWidth > WIDTH) {
                // //长度过长就截取前面部分
                // 长度过长就换行
                String note1 = note.substring(0, note.length() / 2);
                String note2 = note.substring(note.length() / 2, note.length());
                int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg2 = outImage2.createGraphics();
                outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                outg2.setColor(Color.BLACK);
                outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
                outg2.drawString(note2, 200 - strWidth2 / 2,outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                outg2.dispose();
                outImage2.flush();
                outImage = outImage2;
            } else {
                outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
            }
            outg.dispose();
            outImage.flush();
            image = outImage;
        }

        image.flush();

        ImageIO.write(image, "png", codeFile); // TODO
        bs = codeFile.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bs;
}