List of usage examples for java.awt.image BufferedImage getSubimage
public BufferedImage getSubimage(int x, int y, int w, int h)
From source file:net.chris54721.infinitycubed.data.Account.java
public void fetchSkin(boolean update) { if (nickname != null) { LogHelper.info("Fetching skin for player " + getNickname()); BufferedImage skin = Utils.toBufferedImage(Utils.getImageResource("steve")); FileInputStream skinStream = null; boolean fetch = true; try {// w w w .j av a 2 s .c o m File skinFile = Resources.getFile(Resources.ResourceType.SKIN, getNickname() + ".png"); if (update) { URL skinURL = Resources.getUrl(Resources.ResourceType.SKIN, getNickname() + ".png"); Downloadable skinDownloadable = new Downloadable(skinURL, skinFile); if (!skinDownloadable.download()) fetch = false; } else if (!skinFile.isFile()) fetch = false; if (fetch) { skinStream = new FileInputStream(skinFile); skin = ImageIO.read(skinStream); BufferedImage head = skin.getSubimage(8, 8, 8, 8); BufferedImage mask = skin.getSubimage(40, 8, 8, 8); skin = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB); Graphics resultG = skin.getGraphics(); resultG.drawImage(head, 0, 0, null); resultG.drawImage(mask, 0, 0, null); } this.skin = skin; this.skinHead = skin.getScaledInstance(32, 32, Image.SCALE_DEFAULT); } catch (Exception e) { LogHelper.error("Couldn't fetch player skin", e); } finally { if (skinStream != null) IOUtils.closeQuietly(skinStream); } } }
From source file:Controller.UserController.java
@RequestMapping(value = "/UploadImage", method = RequestMethod.POST) public @ResponseBody String uploadProviderImage(@RequestParam("providerImage") MultipartFile providerImage, @RequestParam("providerID") int providerID, HttpSession session) { try {/* w w w .ja v a 2 s . c om*/ String path = System.getProperty("catalina.base"); File folderPackage = new File(path + "/webapps/Images/Tripper/" + providerID); if (!folderPackage.exists()) { folderPackage.mkdirs(); } String extension = FilenameUtils.getExtension(providerImage.getOriginalFilename()); String name = "tripper." + extension; String name2 = "avatar." + extension; // get Bytes and crop byte[] imageInByte = providerImage.getBytes(); InputStream in = new ByteArrayInputStream(imageInByte); BufferedImage bImageFromConvert = ImageIO.read(in); // create a cropped image from the original image BufferedImage croppedImage = bImageFromConvert.getSubimage(0, 0, 100, 100); // // then convert BufferedImage to byte array to save // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ImageIO.write(croppedImage, extension, baos); // baos.flush(); // imageInByte = baos.toByteArray(); // baos.close(); ImageIO.write(croppedImage, extension, new File(folderPackage, name2)); FileCopyUtils.copy(providerImage.getBytes(), new FileOutputStream(new File(folderPackage, name))); String image = "Images/Tripper/" + providerID + "/" + name; AccountSession account = (AccountSession) session.getAttribute("account"); account.setImage(image); session.setAttribute("account", account); tripperService.updateTripperImage(providerID, image); return image; } catch (Exception e) { String content = "Function: ProviderController - uploadProviderImage\n" + "***Input***\n" + "providerID: " + providerID + "\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********"; errorService.logBugWithAccount(content, session, e); return "{\"result\": \"error\"}"; } }
From source file:net.cloudkit.relaxation.VerifyImage.java
public BufferedImage autoCrop(BufferedImage image) { int iw = image.getWidth(); int ih = image.getHeight(); int x = iw;/*from ww w .j a v a2 s. c o m*/ int y = ih; int x2 = 0; int y2 = 0; for (int i = 0; i < iw; ++i) { for (int j = 0; j < ih; ++j) { int rgb = getRed(image.getRGB(i, j)); if (rgb != 255) { x = Math.min(i, x); y = Math.min(j, y); x2 = Math.max(i, x2); y2 = Math.max(j, y2); } } } return image.getSubimage(x, y, x2 - x + 1, y2 - y + 1); }
From source file:com.sat.dbds.vcs.login.LoginStepDef.java
/** * Start scenario/* ww w .ja va2s . c o m*/ * <pre> * <b> Gherkin </b> * <code> @Before(order = 1)</code> * </pre>. * * @param by the by * @param loc the loc * @throws IOException Signals that an I/O exception has occurred. */ void DownloadImage(By by, String loc) throws IOException { WebElement Image = SeleniumUtilities.getDriver().findElement(by); File screen = ((TakesScreenshot) SeleniumUtilities.getDriver()).getScreenshotAs(OutputType.FILE); int width = Image.getSize().getWidth(); int height = Image.getSize().getHeight(); BufferedImage img = ImageIO.read(screen); BufferedImage dest = img.getSubimage(Image.getLocation().getX(), Image.getLocation().getY(), width, height); ImageIO.write(dest, "png", screen); File file = new File(loc); FileUtils.copyFile(screen, file); }
From source file:com.galenframework.api.GalenPageDump.java
public void exportAllScreenshots(PageDump pageDump, Browser browser, File reportFolder) throws IOException { File screenshotOriginalFile = browser.getPage().getScreenshotFile(); FileUtils.copyFile(screenshotOriginalFile, new File(reportFolder.getAbsolutePath() + File.separator + "page.png")); BufferedImage image = Rainbow4J.loadImage(screenshotOriginalFile.getAbsolutePath()); File objectsFolder = new File(reportFolder.getAbsolutePath() + File.separator + "objects"); objectsFolder.mkdirs();//from w w w . ja va2 s . c o m for (PageDump.Element element : pageDump.getItems().values()) { if (element.getHasImage()) { int[] area = element.getArea(); if (area[0] < image.getWidth() && area[1] < image.getHeight()) { int x = Math.max(area[0], 0); int y = Math.max(area[1], 0); int x2 = Math.min(area[0] + area[2], image.getWidth()); int y2 = Math.min(area[1] + area[3], image.getHeight()); int availableWidth = x2 - x; int availableHeight = y2 - y; try { if (availableWidth > 0 && availableHeight > 0) { BufferedImage subImage = image.getSubimage(x, y, availableWidth, availableHeight); Rainbow4J.saveImage(subImage, new File(objectsFolder.getAbsolutePath() + File.separator + element.getObjectName() + ".png")); } else { element.setHasImage(false); } } catch (Exception ex) { LOG.error("Got error during saving image", ex); } } } } }
From source file:com.netease.dagger.BrowserEmulator.java
/** * Get cell webelement prepare for image code auto-authentication * combine with Tesseract-OCR//from ww w .ja v a2s.c om */ public void screenShotForElement(RemoteWebDriver driver, WebElement element, String path) { File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try { Point p = element.getLocation(); int width = element.getSize().getWidth(); int height = element.getSize().getHeight(); Rectangle rect = new Rectangle(width, height); BufferedImage img = ImageIO.read(scrFile); BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width, rect.height); ImageIO.write(dest, "png", scrFile); Thread.sleep(1000); FileUtils.copyFile(scrFile, new File(path)); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.sketchy.image.ImageProcessingThread.java
public static BufferedImage resizeImage(BufferedImage image, int drawingWidth, int drawingHeight, CenterOption centerOption, ScaleOption scaleOption) { int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); double widthScale = drawingWidth / (double) imageWidth; double heightScale = drawingHeight / (double) imageHeight; double scale = Math.min(widthScale, heightScale); int scaleWidth = (int) (imageWidth * scale); int scaleHeight = (int) (imageHeight * scale); BufferedImage resizedImage = new BufferedImage(scaleWidth, scaleHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = resizedImage.createGraphics(); if (scaleOption == ScaleOption.SCALE_AREA_AVERAGING) { ImageProducer prod = new FilteredImageSource(image.getSource(), new AreaAveragingScaleFilter(scaleWidth, scaleHeight)); Image img = Toolkit.getDefaultToolkit().createImage(prod); g.drawImage(img, 0, 0, scaleWidth, scaleHeight, null); // it's already scaled } else {//from ww w . j a va2 s . co m if (scaleOption == ScaleOption.SCALE_NEAREST_NEIGHBOR) { g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } else if (scaleOption == ScaleOption.SCALE_BICUBIC) { g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); } else if (scaleOption == ScaleOption.SCALE_BILINEAR) { g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } g.drawImage(image, 0, 0, scaleWidth, scaleHeight, 0, 0, imageWidth, imageHeight, null); } g.dispose(); int cropWidth = (int) Math.min(scaleWidth, drawingWidth); int cropHeight = (int) Math.min(scaleHeight, drawingHeight); int drawingLeft = 0; int drawingTop = 0; if ((centerOption == CenterOption.CENTER_HORIZONTAL) || (centerOption == CenterOption.CENTER_BOTH)) { drawingLeft = (int) ((drawingWidth - cropWidth) / 2.0); } if ((centerOption == CenterOption.CENTER_VERTICAL) || (centerOption == CenterOption.CENTER_BOTH)) { drawingTop = (int) ((drawingHeight - cropHeight) / 2.0); } BufferedImage croppedImage = resizedImage.getSubimage(0, 0, cropWidth, cropHeight); resizedImage = null; BufferedImage drawingImage = new BufferedImage(drawingWidth, drawingHeight, BufferedImage.TYPE_INT_ARGB); g = drawingImage.createGraphics(); g.drawImage(croppedImage, drawingLeft, drawingTop, drawingLeft + cropWidth, drawingTop + cropHeight, 0, 0, cropWidth, cropHeight, null); g.dispose(); croppedImage = null; return drawingImage; }
From source file:org.wallride.web.support.MediaHttpRequestHandler.java
private void resizeImage(Resource resource, File file, int width, int height, Media.ResizeMode mode) throws IOException { long startTime = System.currentTimeMillis(); if (width <= 0) { width = Integer.MAX_VALUE; }/*from ww w. ja v a2 s .c o m*/ if (height <= 0) { height = Integer.MAX_VALUE; } BufferedImage image = ImageIO.read(resource.getInputStream()); ResampleOp resampleOp; BufferedImage resized; switch (mode) { case RESIZE: resampleOp = new ResampleOp(DimensionConstrain.createMaxDimension(width, height, true)); resampleOp.setFilter(ResampleFilters.getLanczos3Filter()); resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Normal); resized = resampleOp.filter(image, null); ImageIO.write(resized, StringUtils.getFilenameExtension(file.getName()), file); break; case CROP: float wr = (float) width / (float) image.getWidth(); float hr = (float) height / (float) image.getHeight(); float fraction = (wr > hr) ? wr : hr; if (fraction < 1) { resampleOp = new ResampleOp(DimensionConstrain.createRelativeDimension(fraction)); resampleOp.setFilter(ResampleFilters.getLanczos3Filter()); resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Normal); resized = resampleOp.filter(image, null); } else { resized = image; } if (resized.getWidth() > width) { resized = resized.getSubimage((resized.getWidth() - width) / 2, 0, width, resized.getHeight()); } else if (resized.getHeight() > height) { resized = resized.getSubimage(0, (resized.getHeight() - height) / 2, resized.getWidth(), height); } ImageIO.write(resized, StringUtils.getFilenameExtension(file.getName()), file); break; default: throw new IllegalStateException(); } long stopTime = System.currentTimeMillis(); logger.debug("Resized image: time [{}ms]", stopTime - startTime); }
From source file:fr.gael.dhus.datastore.processing.impl.ProcessingUtils.java
/** * Cut the quicklook that have a big width/height ratio. * Each sub-part is dispatched on multiple bands. * * @param quick_look the quick_look to be cut * @param max_ratio the maximum ratio between quick_look width and height. * @param margin the margin between each band. default 5. */// w w w . j a v a 2s . c o m public static RenderedImage cutQuickLook(RenderedImage input_image, double max_ratio, int margin) { ColorModel color_model = input_image.getColorModel(); if ((color_model == null) && (input_image.getSampleModel() != null)) { color_model = ColorRenderer.createColorModel(input_image.getSampleModel()); } BufferedImage quick_look; try { quick_look = PlanarImage.wrapRenderedImage(input_image).getAsBufferedImage( new Rectangle(input_image.getWidth(), input_image.getHeight()), color_model); } catch (Exception e) { logger.error("Problem getting buffered image.", e); throw new IllegalArgumentException("Problem getting buffered image", e); } if ((quick_look != null) && ((quick_look.getWidth() > 0) && (quick_look.getHeight() > 0))) { //Compute width/height ratio int ql_width = quick_look.getWidth(); int ql_height = quick_look.getHeight(); int ratio = (int) Math.sqrt(Math.max(ql_width, ql_height) / Math.min(ql_width, ql_height)); //Check if the quicklook has a strong width/height ratio if ((ratio < max_ratio) || (ratio <= 1)) return PlanarImage.wrapRenderedImage(quick_look); /** * Cut the wider side (width or height) into "ratio" bands. * Ex: If height = 3 * width then we cut 3 bands along columns * So height' = height / 3 (extract 1 band / 3 from height) * width' = width * 3 (dispatch 3 bands along lines) */ int width = ql_width; //width of the bands int height = ql_height; //height of the bands if (ql_width < ql_height) //cut along height { width = (ql_width + margin) * ratio; height = ql_height / ratio; } else //cut along width { width = ql_width / ratio; height = (ql_height + margin) * ratio; } //Dispatch the sub-parts BufferedImage quick_look_cut = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = quick_look_cut.createGraphics(); for (int k = 0; k < ratio; k++) { BufferedImage ql_band = null; //Dispatch on columns if (ql_width < ql_height) { ql_band = quick_look.getSubimage(0, (k * ql_height) / ratio, ql_width, ql_height / ratio); g2.drawImage(ql_band, null, k * (ql_width + margin), 0); } //Dispatch on lines else { ql_band = quick_look.getSubimage((k * ql_width) / ratio, 0, ql_width / ratio, ql_height); g2.drawImage(ql_band, null, 0, k * (ql_height + margin)); } } //for each band g2.dispose(); return PlanarImage.wrapRenderedImage(quick_look_cut); } return PlanarImage.wrapRenderedImage(quick_look); }
From source file:de.tor.tribes.ui.panels.MinimapPanel.java
/** * Creates new form MinimapPanel//from ww w.j a va2s . co m */ MinimapPanel() { initComponents(); setSize(300, 300); mMinimapListeners = new LinkedList<>(); mToolChangeListeners = new LinkedList<>(); setCursor(ImageManager.getCursor(iCurrentCursor)); mScreenshotPanel = new ScreenshotPanel(); minimapButtons.put(ID_MINIMAP, new Rectangle(2, 2, 26, 26)); minimapButtons.put(ID_ALLY_CHART, new Rectangle(30, 2, 26, 26)); minimapButtons.put(ID_TRIBE_CHART, new Rectangle(60, 2, 26, 26)); try { minimapIcons.put(ID_MINIMAP, ImageIO.read(new File("./graphics/icons/minimap.png"))); minimapIcons.put(ID_ALLY_CHART, ImageIO.read(new File("./graphics/icons/ally_chart.png"))); minimapIcons.put(ID_TRIBE_CHART, ImageIO.read(new File("./graphics/icons/tribe_chart.png"))); } catch (Exception ignored) { } jPanel1.add(mScreenshotPanel); rVisiblePart = new Rectangle(ServerSettings.getSingleton().getMapDimension()); zoomed = false; MarkerManager.getSingleton().addManagerListener(this); TagManager.getSingleton().addManagerListener(this); MinimapRepaintThread.getSingleton().setVisiblePart(rVisiblePart); if (!GlobalOptions.isMinimal()) { MinimapRepaintThread.getSingleton().start(); } addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (!showControls && e.getButton() != MouseEvent.BUTTON1) { //show controls Point p = e.getPoint(); p.translate(-5, -5); showControls(p); return; } if (!showControls && iCurrentView == ID_MINIMAP) { Point p = mousePosToMapPosition(e.getX(), e.getY()); DSWorkbenchMainFrame.getSingleton().centerPosition(p.getX(), p.getY()); MapPanel.getSingleton().getMapRenderer().initiateRedraw(MapRenderer.ALL_LAYERS); if (MinimapZoomFrame.getSingleton().isVisible()) { MinimapZoomFrame.getSingleton().toFront(); } } else { if (minimapButtons.get(ID_MINIMAP).contains(e.getPoint())) { iCurrentView = ID_MINIMAP; mBuffer = null; showControls = false; MinimapRepaintThread.getSingleton().update(); } else if (minimapButtons.get(ID_ALLY_CHART).contains(e.getPoint())) { iCurrentView = ID_ALLY_CHART; lastHash = 0; showControls = false; updateComplete(); } else if (minimapButtons.get(ID_TRIBE_CHART).contains(e.getPoint())) { iCurrentView = ID_TRIBE_CHART; lastHash = 0; showControls = false; updateComplete(); } } } @Override public void mousePressed(MouseEvent e) { if (iCurrentView != ID_MINIMAP) { return; } if (iCurrentCursor == ImageManager.CURSOR_SHOT || iCurrentCursor == ImageManager.CURSOR_ZOOM) { iXDown = e.getX(); iYDown = e.getY(); } } @Override public void mouseReleased(MouseEvent e) { if (iCurrentView != ID_MINIMAP) { return; } if (rDrag == null) { return; } if (iCurrentCursor == ImageManager.CURSOR_SHOT) { try { BufferedImage i = MinimapRepaintThread.getSingleton().getImage(); double widthFactor = ((double) ServerSettings.getSingleton().getMapDimension().width) / getWidth(); double heightFactor = ((double) ServerSettings.getSingleton().getMapDimension().height) / getHeight(); int x = (int) Math.rint(widthFactor * rDrag.getX()); int y = (int) Math.rint(heightFactor * rDrag.getY()); int w = (int) Math.rint(widthFactor * (rDrag.getWidth() - rDrag.getX())); int h = (int) Math.rint(heightFactor * (rDrag.getHeight() - rDrag.getY())); BufferedImage sub = i.getSubimage(x, y, w, h); mScreenshotPanel.setBuffer(sub); jPanel1.setSize(mScreenshotPanel.getSize()); jPanel1.setPreferredSize(mScreenshotPanel.getSize()); jPanel1.setMinimumSize(mScreenshotPanel.getSize()); jPanel1.setMaximumSize(mScreenshotPanel.getSize()); jScreenshotPreview.pack(); jScreenshotControl.pack(); jScreenshotPreview.setVisible(true); jScreenshotControl.setVisible(true); } catch (Exception ie) { logger.error("Failed to initialize mapshot", ie); } } else if (iCurrentCursor == ImageManager.CURSOR_ZOOM) { if (!zoomed) { Rectangle mapDim = ServerSettings.getSingleton().getMapDimension(); double widthFactor = ((double) mapDim.width) / getWidth(); double heightFactor = ((double) mapDim.height) / getHeight(); int x = (int) Math.rint(widthFactor * rDrag.getX() + mapDim.getMinX()); int y = (int) Math.rint(heightFactor * rDrag.getY() + mapDim.getMinY()); int w = (int) Math.rint(widthFactor * (rDrag.getWidth() - rDrag.getX())); if (w >= 10) { rVisiblePart = new Rectangle(x, y, w, w); MinimapRepaintThread.getSingleton().setVisiblePart(rVisiblePart); redraw(); zoomed = true; } } else { rVisiblePart = new Rectangle(ServerSettings.getSingleton().getMapDimension()); MinimapRepaintThread.getSingleton().setVisiblePart(rVisiblePart); redraw(); zoomed = false; } MinimapZoomFrame.getSingleton().setVisible(false); } iXDown = 0; iYDown = 0; rDrag = null; } @Override public void mouseEntered(MouseEvent e) { if (iCurrentView != ID_MINIMAP) { return; } switch (iCurrentCursor) { case ImageManager.CURSOR_ZOOM: { MinimapZoomFrame.getSingleton().setVisible(true); } } } @Override public void mouseExited(MouseEvent e) { if (MinimapZoomFrame.getSingleton().isVisible()) { MinimapZoomFrame.getSingleton().setVisible(false); } iXDown = 0; iYDown = 0; rDrag = null; } }); addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e) { if (iCurrentView != ID_MINIMAP) { return; } switch (iCurrentCursor) { case ImageManager.CURSOR_MOVE: { Point p = mousePosToMapPosition(e.getX(), e.getY()); DSWorkbenchMainFrame.getSingleton().centerPosition(p.x, p.y); rDrag = null; break; } case ImageManager.CURSOR_SHOT: { rDrag = new Rectangle2D.Double(iXDown, iYDown, e.getX(), e.getY()); break; } case ImageManager.CURSOR_ZOOM: { rDrag = new Rectangle2D.Double(iXDown, iYDown, e.getX(), e.getY()); break; } } } @Override public void mouseMoved(MouseEvent e) { if (iCurrentView == ID_MINIMAP) { switch (iCurrentCursor) { case ImageManager.CURSOR_ZOOM: { if (!MinimapZoomFrame.getSingleton().isVisible()) { MinimapZoomFrame.getSingleton().setVisible(true); } int mapWidth = (int) ServerSettings.getSingleton().getMapDimension().getWidth(); int mapHeight = (int) ServerSettings.getSingleton().getMapDimension().getHeight(); int x = (int) Math.rint((double) mapWidth / (double) getWidth() * (double) e.getX()); int y = (int) Math.rint((double) mapHeight / (double) getHeight() * (double) e.getY()); MinimapZoomFrame.getSingleton().updatePosition(x, y); break; } default: { if (MinimapZoomFrame.getSingleton().isVisible()) { MinimapZoomFrame.getSingleton().setVisible(false); } } } } Point location = minimapButtons.get(ID_MINIMAP).getLocation(); location.translate(-2, -2); if (!new Rectangle(location.x, location.y, 88, 30).contains(e.getPoint())) { //hide controls showControls = false; repaint(); } } }); addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { if (iCurrentView != ID_MINIMAP) { return; } iCurrentCursor += e.getWheelRotation(); if (iCurrentCursor == ImageManager.CURSOR_DEFAULT + e.getWheelRotation()) { if (e.getWheelRotation() < 0) { iCurrentCursor = ImageManager.CURSOR_SHOT; } else { iCurrentCursor = ImageManager.CURSOR_MOVE; } } else if (iCurrentCursor < ImageManager.CURSOR_MOVE) { iCurrentCursor = ImageManager.CURSOR_DEFAULT; } else if (iCurrentCursor > ImageManager.CURSOR_SHOT) { iCurrentCursor = ImageManager.CURSOR_DEFAULT; } if (iCurrentCursor != ImageManager.CURSOR_ZOOM) { if (MinimapZoomFrame.getSingleton().isVisible()) { MinimapZoomFrame.getSingleton().setVisible(false); } } else { MinimapZoomFrame.getSingleton().setVisible(true); } setCurrentCursor(iCurrentCursor); } }); }