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

The following examples show how to use java.awt.image.BufferedImage#getWidth() . 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
ClueScrollWorldMapPoint(final WorldPoint worldPoint, ClueScrollPlugin plugin)
{
	super(worldPoint, null);

	clueScrollWorldImage = new BufferedImage(plugin.getMapArrow().getWidth(), plugin.getMapArrow().getHeight(), BufferedImage.TYPE_INT_ARGB);
	Graphics graphics = clueScrollWorldImage.getGraphics();
	graphics.drawImage(plugin.getMapArrow(), 0, 0, null);
	graphics.drawImage(plugin.getClueScrollImage(), 0, 0, null);
	clueScrollWorldImagePoint = new Point(
		clueScrollWorldImage.getWidth() / 2,
		clueScrollWorldImage.getHeight());

	this.plugin = plugin;
	this.setSnapToEdge(true);
	this.setJumpOnClick(true);
	this.setImage(clueScrollWorldImage);
	this.setImagePoint(clueScrollWorldImagePoint);
}
 
Example 2
Rectangle getPixelsOutline(BufferedImage img) {
    int x1 = 0;
    while (x1 < img.getWidth() && isLineEmpty(img, x1, false)) {
        x1++;
    }
    int x2 = img.getWidth() - 1;
    while (x2 >= 0 && isLineEmpty(img, x2, false)) {
        x2--;
    }
    int y1 = 0;
    while (y1 < img.getHeight() && isLineEmpty(img, y1, true)) {
        y1++;
    }
    int y2 = img.getHeight() - 1;
    while (y2 >= 0 && isLineEmpty(img, y2, true)) {
        y2--;
    }

    return new Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
}
 
Example 3
Source Project: PolyGlot   File: ImageNode.java    License: MIT License 6 votes vote down vote up
private boolean bufferedImagesEqual(BufferedImage img1, BufferedImage img2) {
    boolean ret = true;

    if (img1.getWidth() == img2.getWidth() && img1.getHeight() == img2.getHeight()) {
        for (int x = 0; x < img1.getWidth() && ret; x++) {
            for (int y = 0; y < img1.getHeight() && ret; y++) {
                if (img1.getRGB(x, y) != img2.getRGB(x, y)) {
                    ret = false;
                }
            }
        }
    } else {
        ret = false;
    }

    return ret;
}
 
Example 4
public BufferedImage filter(BufferedImage bi, BufferedImage dest) {
    int width = bi.getWidth();
    int height = bi.getHeight();
    pixels = new int[width * height];
    bi.getRGB(0, 0, width, height, pixels, 0, width);
    BufferedImage dstBi = new BufferedImage(width, height, bi.getType());

    if (colors) {
        autoColor();
    }
    if (contrast) {
        autoContrast();
    }
    if (levels) {
        autoLevels();
    }

    dstBi.setRGB(0, 0, width, height, pixels, 0, width);

    return dstBi;
}
 
Example 5
public void setCursor(ResourceLocation cursor) {
    try {
        BufferedImage image = ImageIO.read(Minecraft.getMinecraft().getResourceManager().getResource(cursor).getInputStream());
        int w = image.getWidth();
        int h = image.getHeight();
        int[] pixels = new int[(w * h)];
        image.getRGB(0, 0, w, h, pixels, 0, w);
        ByteBuffer buffer = BufferUtils.createByteBuffer(w * h * 4);

        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                int pixel = pixels[(h - 1 - y) * w + x];
                buffer.put((byte) (pixel & 0xFF));
                buffer.put((byte) (pixel >> 8 & 0xFF));
                buffer.put((byte) (pixel >> 16 & 0xFF));
                buffer.put((byte) (pixel >> 24 & 0xFF));
            }
        }

        buffer.flip();
        Mouse.setNativeCursor(new Cursor(w, h, 0, h - 1, 1, buffer.asIntBuffer(), null));
    } catch (Exception ignored) {
    }
}
 
Example 6
@Override
public BufferedImage filter(BufferedImage src, BufferedImage dst) {
    if (blurMethod == BOX3_BLUR) {
        if ((src.getWidth() == 1) || (src.getHeight() == 1)) {
            // otherwise we get ArrayIndexOutOfBoundsException in BoxBlurFilter
            return src;
        }
        dst = new BoxBlurFilter(radius, radius, 3, filterName).filter(src, null);
    } else if (blurMethod == GAUSSIAN_BLUR) {
        dst = new GaussianFilter(radius, filterName).filter(src, null);
    } else {
        throw new IllegalStateException("blurMethod = " + blurMethod);
    }

    lowerThreshold3 = 255 * 3 * (threshold - softness * 0.5f);
    upperThreshold3 = 255 * 3 * (threshold + softness * 0.5f);
    return super.filter(dst, dst);
}
 
Example 7
public static Image getScaledInstance(File file) throws Exception {
	BufferedImage srcBImage = ImageIO.read(file);

	if (srcBImage.getWidth() > srcBImage.getHeight()) {
		width = 100;
		height = srcBImage.getHeight() * 100 / srcBImage.getWidth();
	} else {
		height = 100;
		width = srcBImage.getWidth() * 100 / srcBImage.getHeight();
	}

	dest = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
	dest2 = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

	g = dest.getGraphics();
	g.setColor(Color.white);
	g.fillRect(0, 0, 100, 100);
	g.drawImage(srcBImage, 0, 0, width, height, null);

	g.dispose();
	blurOperator.filter(dest, dest2);

	return dest2;
}
 
Example 8
protected boolean moveRectIntoImage(Rectangle2D searchRect) {
	// if needed, modify search rectangle to keep it within the video image
	BufferedImage image = trackerPanel.getVideo().getImage();
	int w = image.getWidth();
	int h = image.getHeight();
Point2D corner = new Point2D.Double(searchRect.getX(), searchRect.getY());
Dimension dim = new Dimension((int)searchRect.getWidth(), (int)searchRect.getHeight());

	boolean changed = false;
// reduce size if needed
if (w < dim.width || h < dim.height) {
	changed = true;
	dim.setSize(Math.min(w, dim.width), Math.min(h, dim.height)); 
	searchRect.setFrame(corner, dim);
}

// move corner point if needed
double x = Math.max(0, corner.getX());
x = Math.min(x, w-dim.width); 
double y = Math.max(0, corner.getY());
y = Math.min(y, h-dim.height);
if (x!=corner.getX() || y!=corner.getY()) {
	changed = true;
	corner.setLocation(x, y);
	searchRect.setFrame(corner, dim);
}

return changed;		
}
 
Example 9
Source Project: sambox   File: JPEGFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateFromImage4BYTE_ABGR() throws IOException
{
    // workaround Open JDK bug
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7044758
    if (System.getProperty("java.runtime.name").equals("OpenJDK Runtime Environment")
            && (System.getProperty("java.specification.version").equals("1.6")
                    || System.getProperty("java.specification.version").equals("1.7")
                    || System.getProperty("java.specification.version").equals("1.8")))
    {
        return;
    }

    PDDocument document = new PDDocument();
    BufferedImage image = ImageIO.read(JPEGFactoryTest.class.getResourceAsStream("jpeg.jpg"));

    // create an ARGB image
    int width = image.getWidth();
    int height = image.getHeight();
    BufferedImage argbImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics ag = argbImage.getGraphics();
    ag.drawImage(image, 0, 0, null);
    ag.dispose();

    for (int x = 0; x < argbImage.getWidth(); ++x)
    {
        for (int y = 0; y < argbImage.getHeight(); ++y)
        {
            argbImage.setRGB(x, y, (argbImage.getRGB(x, y) & 0xFFFFFF) | ((y / 10 * 10) << 24));
        }
    }

    PDImageXObject ximage = JPEGFactory.createFromImage(argbImage);
    validate(ximage, 8, width, height, "jpg", PDDeviceRGB.INSTANCE.getName());
    assertNotNull(ximage.getSoftMask());
    validate(ximage.getSoftMask(), 8, width, height, "jpg", PDDeviceGray.INSTANCE.getName());
    assertTrue(colorCount(ximage.getSoftMask().getImage()) > image.getHeight() / 10);

    doWritePDF(document, ximage, testResultsDir, "jpeg-4bargb.pdf");
}
 
Example 10
Source Project: easyCV   File: ImageView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 使用窗口显示BufferedImage图片
 * @param image -BufferedImage
 */
public static void show(BufferedImage image) {
	int width=image.getWidth(),height=image.getHeight();
	Console.log(width+","+height);
	JLabel label = new JLabel();
	label.setSize(width, height);
	
	label.setIcon(new ImageIcon(image));

	JFrame frame = new JFrame();
	frame.setSize(width, height);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.add(label);
	frame.setVisible(true);
}
 
Example 11
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id, Integer width, Integer height)
		throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo> result = new ActionResult<>();
		Attachment2 attachment = emc.find(id, Attachment2.class, ExceptionWhen.not_found);
		/* 判断文件的当前用户是否是管理员或者文件创建者 或者当前用户在分享或者共同编辑中 */
		if (effectivePerson.isNotManager() && effectivePerson.isNotPerson(attachment.getPerson())) {
			throw new Exception("person{name:" + effectivePerson.getDistinguishedName() + "} access attachment{id:"
					+ id + "} denied.");
		}
		if (!ArrayUtils.contains(IMAGE_EXTENSIONS, attachment.getExtension())) {
			throw new Exception("attachment not image file.");
		}
		if (width < 0 || width > 5000) {
			throw new Exception("invalid width:" + width + ".");
		}
		if (height < 0 || height > 5000) {
			throw new Exception("invalid height:" + height + ".");
		}
		OriginFile originFile = emc.find(attachment.getOriginFile(),OriginFile.class);
		if (null == originFile) {
			throw new ExceptionAttachmentNotExist(id,attachment.getOriginFile());
		}
		Wo wo = null;
		String cacheKey = ApplicationCache.concreteCacheKey(this.getClass(), id+width+height);
		Element element = cache.get(cacheKey);
		if ((null != element) && (null != element.getObjectValue())) {
			wo = (Wo) element.getObjectValue();
			result.setData(wo);
		} else {
			StorageMapping mapping = ThisApplication.context().storageMappings().get(OriginFile.class,
					originFile.getStorage());
			try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
				originFile.readContent(mapping, output);
				try (ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray())) {
					BufferedImage src = ImageIO.read(input);
					int scalrWidth = (width == 0) ? src.getWidth() : width;
					int scalrHeight = (height == 0) ? src.getHeight() : height;
					Scalr.Mode mode = Scalr.Mode.FIT_TO_WIDTH;
					if(src.getWidth()>src.getHeight()){
						mode = Scalr.Mode.FIT_TO_HEIGHT;
					}
					BufferedImage scalrImage = Scalr.resize(src,Scalr.Method.SPEED, mode, NumberUtils.min(scalrWidth, src.getWidth()),
							NumberUtils.min(scalrHeight, src.getHeight()));
					try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
						ImageIO.write(scalrImage, "png", baos);
						byte[] bs = baos.toByteArray();

						wo = new Wo(bs, this.contentType(false, attachment.getName()),
								this.contentDisposition(false, attachment.getName()));

						cache.put(new Element(cacheKey, wo));
						result.setData(wo);
					}
				}
			}
		}

		return result;
	}
}
 
Example 12
@Override
public BufferedImage apply(BufferedImage img) {
	
	Graphics2D g = img.createGraphics();
	
	int glassHeight = (int) (scale * img.getHeight());
	
	BufferedImage scaledGlass = ImageTools.scaleToHeight(glasses, glassHeight, false);
	
	int x = (int) (xPosition * (img.getWidth()+ scaledGlass.getWidth())) - scaledGlass.getWidth();
	int y = (int) (yPosition * (img.getHeight()+ scaledGlass.getHeight())) - scaledGlass.getHeight();
	
	g.drawImage(scaledGlass, x, y, null);
	
	return img;
}
 
Example 13
private BufferedImage create_LCD_Image(final int WIDTH, final int HEIGHT) {
    if (WIDTH <= 0 || HEIGHT <= 0) {
        return null;
    }

    final BufferedImage IMAGE = UTIL.createImage(WIDTH, HEIGHT, Transparency.TRANSLUCENT);
    final Graphics2D G2 = IMAGE.createGraphics();
    G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    G2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
    G2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    final int IMAGE_WIDTH = IMAGE.getWidth();
    final int IMAGE_HEIGHT = IMAGE.getHeight();

    // Background rectangle
    final Point2D BACKGROUND_START = new Point2D.Double(0.0, 0.0);
    final Point2D BACKGROUND_STOP = new Point2D.Double(0.0, IMAGE_HEIGHT);
    if (BACKGROUND_START.equals(BACKGROUND_STOP)) {
        BACKGROUND_STOP.setLocation(0.0, BACKGROUND_START.getY() + 1);
    }

    final float[] BACKGROUND_FRACTIONS = {
        0.0f,
        0.08f,
        0.92f,
        1.0f
    };

    final Color[] BACKGROUND_COLORS = {
        new Color(0.4f, 0.4f, 0.4f, 1.0f),
        new Color(0.5f, 0.5f, 0.5f, 1.0f),
        new Color(0.5f, 0.5f, 0.5f, 1.0f),
        new Color(0.9f, 0.9f, 0.9f, 1.0f)
    };

    final LinearGradientPaint BACKGROUND_GRADIENT = new LinearGradientPaint(BACKGROUND_START, BACKGROUND_STOP, BACKGROUND_FRACTIONS, BACKGROUND_COLORS);
    //final double BACKGROUND_CORNER_RADIUS = WIDTH * 0.09375;
    final double BACKGROUND_CORNER_RADIUS = WIDTH > HEIGHT ? (HEIGHT * 0.095) : (WIDTH * 0.095);
    final java.awt.geom.RoundRectangle2D BACKGROUND = new java.awt.geom.RoundRectangle2D.Double(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, BACKGROUND_CORNER_RADIUS, BACKGROUND_CORNER_RADIUS);
    G2.setPaint(BACKGROUND_GRADIENT);
    G2.fill(BACKGROUND);

    // Foreground rectangle
    final Point2D FOREGROUND_START = new Point2D.Double(0.0, 1.0);
    final Point2D FOREGROUND_STOP = new Point2D.Double(0.0, IMAGE_HEIGHT - 1);
    if (FOREGROUND_START.equals(FOREGROUND_STOP)) {
        FOREGROUND_STOP.setLocation(0.0, FOREGROUND_START.getY() + 1);
    }

    final float[] FOREGROUND_FRACTIONS = {
        0.0f,
        0.03f,
        0.49f,
        0.5f,
        1.0f
    };

    final Color[] FOREGROUND_COLORS = {
        lcdColor.GRADIENT_START_COLOR,
        lcdColor.GRADIENT_FRACTION1_COLOR,
        lcdColor.GRADIENT_FRACTION2_COLOR,
        lcdColor.GRADIENT_FRACTION3_COLOR,
        lcdColor.GRADIENT_STOP_COLOR
    };

    if (lcdColor == LcdColor.CUSTOM) {
        G2.setPaint(customLcdBackground);
    } else {
        final LinearGradientPaint FOREGROUND_GRADIENT = new LinearGradientPaint(FOREGROUND_START, FOREGROUND_STOP, FOREGROUND_FRACTIONS, FOREGROUND_COLORS);
        G2.setPaint(FOREGROUND_GRADIENT);
    }
    final double FOREGROUND_CORNER_RADIUS = BACKGROUND.getArcWidth() - 1;
    final java.awt.geom.RoundRectangle2D FOREGROUND = new java.awt.geom.RoundRectangle2D.Double(1, 1, IMAGE_WIDTH - 2, IMAGE_HEIGHT - 2, FOREGROUND_CORNER_RADIUS, FOREGROUND_CORNER_RADIUS);
    G2.fill(FOREGROUND);

    G2.dispose();

    return IMAGE;
}
 
Example 14
Source Project: freecol   File: TileViewer.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Displays the given Tile onto the given Graphics2D object at the
 * location specified by the coordinates. Settlements and Lost
 * City Rumours will be shown.
 *
 * @param g The Graphics2D object on which to draw the Tile.
 * @param tile The Tile to draw.
 * @param withNumber Whether to display the number of units present.
 * @param rop An optional RescaleOp for fog of war.
 */
public void displaySettlementWithChipsOrPopulationNumber(Graphics2D g,
    Tile tile, boolean withNumber, RescaleOp rop) {
    final Player player = getMyPlayer();
    final Settlement settlement = tile.getSettlement();

    if (settlement != null) {
        if (settlement instanceof Colony) {
            final Colony colony = (Colony)settlement;

            // Draw image of colony in center of the tile.
            BufferedImage colonyImage = lib.getScaledSettlementImage(settlement);
            displayLargeCenteredImage(g, colonyImage, rop);

            if (withNumber) {
                String populationString
                    = Integer.toString(colony.getApparentUnitCount());
                String bonusString = "color.map.productionBonus."
                    + colony.getProductionBonus();
                // If more units can be added, go larger and use italic
                BufferedImage stringImage
                    = (colony.getPreferredSizeChange() > 0)
                    ? lib.getStringImage(g, populationString, bonusString,
                        FontLibrary.FontType.SIMPLE,
                        FontLibrary.FontSize.SMALLER,
                        Font.BOLD | Font.ITALIC)
                    : lib.getStringImage(g, populationString, bonusString,
                        FontLibrary.FontType.SIMPLE,
                        FontLibrary.FontSize.TINY,
                        Font.BOLD);
                displayCenteredImage(g, stringImage, rop);
            }

        } else if (settlement instanceof IndianSettlement) {
            IndianSettlement is = (IndianSettlement)settlement;
            BufferedImage settlementImage = lib.getScaledSettlementImage(settlement);

            // Draw image of indian settlement in center of the tile.
            displayLargeCenteredImage(g, settlementImage, rop);

            BufferedImage chip;
            float xOffset = STATE_OFFSET_X * lib.getScaleFactor();
            float yOffset = STATE_OFFSET_Y * lib.getScaleFactor();
            final int colonyLabels = getClientOptions()
                .getInteger(ClientOptions.COLONY_LABELS);
            if (colonyLabels != ClientOptions.COLONY_LABELS_MODERN) {
                // Draw the settlement chip
                chip = lib.getIndianSettlementChip(g, is);
                int cWidth = chip.getWidth();
                g.drawImage(chip, rop, (int)xOffset, (int)yOffset);
                xOffset += cWidth + 2;

                // Draw the mission chip if needed.
                Unit missionary = is.getMissionary();
                if (missionary != null) {
                    boolean expert
                        = missionary.hasAbility(Ability.EXPERT_MISSIONARY);
                    g.drawImage(
                        lib.getMissionChip(
                            g, missionary.getOwner(), expert),
                        rop, (int)xOffset, (int)yOffset);
                    xOffset += cWidth + 2;
                }
            }

            // Draw the alarm chip if needed.
            if ((chip = lib.getAlarmChip(g, is, player)) != null) {
                g.drawImage(chip, rop, (int)xOffset, (int)yOffset);
            }
        } else {
            logger.warning("Bogus settlement: " + settlement);
        }
    }
}
 
Example 15
Source Project: javamelody   File: AbstractFilter.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Rectangle2D getBounds2D(BufferedImage src) {
	return new Rectangle(0, 0, src.getWidth(), src.getHeight());
}
 
Example 16
Source Project: Spade   File: RawImage.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static RawImage unwrapBufferedImage(BufferedImage image)
{
	return new RawImage(image.getWidth(), image.getHeight(), ((DataBufferInt) image.getRaster().getDataBuffer()).getData());
}
 
Example 17
/**
 * Extract SIFT features from specified buffered image.
 *
 * @param  bufferedImage  image to process.
 *
 * @return list of extracted features.
 */
private List<Feature> extractFeaturesFromImage(final BufferedImage bufferedImage) {

    final Timer timer = new Timer();
    timer.start();

    // clone provided parameters since they get modified during feature extraction
    final FloatArray2DSIFT.Param siftParameters = coreSiftParameters.clone();
    final int w = bufferedImage.getWidth();
    final int h = bufferedImage.getHeight();
    final int minSize = w < h ? w : h;
    final int maxSize = w > h ? w : h;
    siftParameters.minOctaveSize = (int) (minScale * minSize - 1.0);
    siftParameters.maxOctaveSize = (int) Math.round(maxScale * maxSize);

    LOG.info("extractFeatures: entry, fdSize={}, steps={}, minScale={}, maxScale={}, minOctaveSize={}, maxOctaveSize={}",
             siftParameters.fdSize,
             siftParameters.steps,
             minScale,
             maxScale,
             siftParameters.minOctaveSize,
             siftParameters.maxOctaveSize);

    // Let imagePlus determine correct processor - original use of ColorProcessor resulted in
    // fewer extracted features when bufferedImage was loaded from disk.
    final ImagePlus imagePlus = new ImagePlus("", bufferedImage);

    final FloatArray2DSIFT sift = new FloatArray2DSIFT(siftParameters);
    final SIFT ijSIFT = new SIFT(sift);

    final List<Feature> featureList = new ArrayList<>();
    ijSIFT.extractFeatures(imagePlus.getProcessor(), featureList);

    if (featureList.size() == 0) {

        final StringBuilder sb = new StringBuilder(256);
        sb.append("no features were extracted");

        if (bufferedImage.getWidth() < siftParameters.minOctaveSize) {
            sb.append(" because montage image width (").append(bufferedImage.getWidth());
            sb.append(") is less than SIFT minOctaveSize (").append(siftParameters.minOctaveSize).append(")");
        } else if (bufferedImage.getHeight() < siftParameters.minOctaveSize) {
            sb.append(" because montage image height (").append(bufferedImage.getHeight());
            sb.append(") is less than SIFT minOctaveSize (").append(siftParameters.minOctaveSize).append(")");
        } else if (bufferedImage.getWidth() > siftParameters.maxOctaveSize) {
            sb.append(" because montage image width (").append(bufferedImage.getWidth());
            sb.append(") is greater than SIFT maxOctaveSize (").append(siftParameters.maxOctaveSize).append(")");
        } else if (bufferedImage.getHeight() > siftParameters.maxOctaveSize) {
            sb.append(" because montage image height (").append(bufferedImage.getHeight());
            sb.append(") is greater than SIFT maxOctaveSize (").append(siftParameters.maxOctaveSize).append(")");
        } else {
            sb.append(", not sure why, montage image width (").append(bufferedImage.getWidth());
            sb.append(") or height (").append(bufferedImage.getHeight());
            sb.append(") may be less than maxKernelSize derived from SIFT steps(");
            sb.append(siftParameters.steps).append(")");
        }

        LOG.warn(sb.toString());
    }

    LOG.info("extractFeatures: exit, extracted " + featureList.size() +
             " features, elapsedTime=" + timer.stop() + "ms");

    return featureList;
}
 
Example 18
Source Project: kurento-java   File: BrowserTest.java    License: Apache License 2.0 4 votes vote down vote up
public String ocr(BufferedImage imgBuff) {
  String parsedOut = null;

  try {
    // Color image to pure black and white
    for (int x = 0; x < imgBuff.getWidth(); x++) {
      for (int y = 0; y < imgBuff.getHeight(); y++) {
        Color color = new Color(imgBuff.getRGB(x, y));
        int red = color.getRed();
        int green = color.getBlue();
        int blue = color.getGreen();
        if (red + green + blue > OCR_COLOR_THRESHOLD) {
          red = green = blue = 0; // Black
        } else {
          red = green = blue = 255; // White
        }
        Color col = new Color(red, green, blue);
        imgBuff.setRGB(x, y, col.getRGB());
      }
    }

    // OCR recognition
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(imgBuff, "png", baos);
    byte[] imageBytes = baos.toByteArray();

    TessBaseAPI api = new TessBaseAPI();
    api.Init(null, "eng");
    ByteBuffer imgBB = ByteBuffer.wrap(imageBytes);

    PIX image = pixReadMem(imgBB, imageBytes.length);
    api.SetImage(image);

    // Get OCR result
    BytePointer outText = api.GetUTF8Text();

    // Destroy used object and release memory
    api.End();
    api.close();
    outText.deallocate();
    pixDestroy(image);

    // OCR corrections
    parsedOut = outText.getString().replaceAll("l", "1").replaceAll("Z", "2").replaceAll("O", "0")
        .replaceAll("B", "8").replaceAll("G", "6").replaceAll("S", "8").replaceAll("'", "")
        .replaceAll("‘", "").replaceAll("\\.", ":").replaceAll("E", "8").replaceAll("o", "0")
        .replaceAll("fl", "0").replaceAll("fi", "6").replaceAll("§", "5").replaceAll("I", "1")
        .replaceAll("T", "7").replaceAll("’", "").replaceAll("U", "0").replaceAll("D", "0");
    if (parsedOut.length() > 7) {
      parsedOut = parsedOut.substring(0, 7) + ":" + parsedOut.substring(8, parsedOut.length());
    }
    parsedOut = parsedOut.replaceAll("::", ":");

    // Remove last part (number of frames)
    int iSpace = parsedOut.lastIndexOf(" ");
    if (iSpace != -1) {
      parsedOut = parsedOut.substring(0, iSpace);
    }
  } catch (IOException e) {
    log.warn("IOException in OCR", e);
  }
  return parsedOut;
}
 
Example 19
/**
 * 将商品图片,商品名字画到模版图中
 *
 * @param qrCodeImg  二维码图片
 * @param goodPicUrl 商品图片地址
 * @param goodName   商品名称
 * @return
 * @throws IOException
 */
private byte[] drawPicture(InputStream qrCodeImg, String goodPicUrl, String goodName) throws IOException {
    //底图
    ClassPathResource redResource = new ClassPathResource("back.png");
    BufferedImage red = ImageIO.read(redResource.getInputStream());


    //商品图片
    URL goodPic = new URL(goodPicUrl);
    BufferedImage goodImage = ImageIO.read(goodPic);

    //小程序二维码
    BufferedImage qrCodeImage = ImageIO.read(qrCodeImg);

    // --- 画图 ---

    //底层空白 bufferedImage
    BufferedImage baseImage = new BufferedImage(red.getWidth(), red.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE);

    //画上图片
    drawImgInImg(baseImage, red, 0, 0, red.getWidth(), red.getHeight());

    //画上商品图片
    drawImgInImg(baseImage, goodImage, 71, 69, 660, 660);

    //画上小程序二维码
    drawImgInImg(baseImage, qrCodeImage, 448, 767, 300, 300);

    //写上商品名称
    drawTextInImg(baseImage, goodName, 65, 867);

    //写上商城名称
    //        drawTextInImgCenter(baseImage, shopName, 98);


    //转jpg
    BufferedImage result = new BufferedImage(baseImage.getWidth(), baseImage
            .getHeight(), BufferedImage.TYPE_3BYTE_BGR);
    result.getGraphics().drawImage(baseImage, 0, 0, null);
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    ImageIO.write(result, "jpg", bs);

    //最终byte数组
    return bs.toByteArray();
}
 
Example 20
Source Project: pumpernickel   File: BufferedAnimation.java    License: MIT License 3 votes vote down vote up
/**
 * Add a frame to this animation.
 * 
 * @param bi
 *            the image to append. This must be the width and height of this
 *            animation.
 * @param cloneImage
 *            if true then this image will be cloned. Because this animation
 *            is represented as a series of <code>BufferedImages</code>
 *            stored in memory: you must clone the image if you want to
 *            continually pass the same <code>BufferedImage</code> to this
 *            method. (Otherwise all previous frames will be corrupt.) If
 *            you always pass a unique <code>BufferedImage</code> to this
 *            method: then this argument can be false.
 * @param duration
 *            the duration (in ms) of this frame.
 * 
 * @throws IOException
 *             if a problem occurs writing the frame data.
 */
public synchronized void addFrame(BufferedImage bi, boolean cloneImage,
		int duration) throws IOException {
	if (cloneImage) {
		BufferedImage clone = new BufferedImage(bi.getWidth(),
				bi.getHeight(), bi.getType());
		Graphics2D g = clone.createGraphics();
		g.drawImage(bi, 0, 0, null);
		g.dispose();
	}
	addFrame(bi, duration);
}