/** * create image thumbnail * * @param width * @param exact fix exactly width and height (might stretch image) */ public void createThumbnail(int width, boolean exact) { if (exact) // resize image to fit exactly image = Scalr.resize(image, Scalr.Mode.FIT_EXACT, width); else image = Scalr.resize(image, width); }
/** * Paints the panel and its image at the current zoom level, location, and interpolation method * dependent on the image scale. * * @param g the <code>Graphics</code> context for painting */ @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; super.paintComponent(g); // Paints the background if (image == null) { return; } if (rotateImageAccordingToExif) { image = rotateAccordingToExif(imageFile, image); rotateImageAccordingToExif = false; if (isNavigationImageEnabled()) { createNavigationImage(image); } } if (scale == 0.0) { initializeScalingParams(); } Rectangle rect = getImageClipBounds(); if (rect == null || rect.width == 0 || rect.height == 0) { // no part of image is displayed in the panel return; } BufferedImage subimage = image.getSubimage(rect.x, rect.y, rect.width, rect.height); Method method; if (isHighQualityRendering()) { method = highQualityScalingMethodToUse; } else { method = Method.SPEED; } int width = Math.min((int) (subimage.getWidth() * scale), getWidth()); int height = Math.min((int) (subimage.getHeight() * scale), getHeight()); if (width > 10 && height > 10) { subimage = Scalr.resize(subimage, method, Mode.FIT_EXACT, width, height); g2.drawImage(subimage, Math.max(0, originX), Math.max(0, originY), null); // Draw navigation image if (isNavigationImageEnabled()) { g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); g2.drawImage( navigationImage, 0, 0, getScreenNavImageWidth(), getScreenNavImageHeight(), null); g.setColor(Color.RED); g.drawLine( 0, getScreenNavImageHeight(), getScreenNavImageWidth(), getScreenNavImageHeight()); g.drawLine( getScreenNavImageWidth(), 0, getScreenNavImageWidth(), getScreenNavImageHeight()); drawZoomAreaOutline(g); } } }
@Override protected AbstractView doService() throws MvcException { UserInfo userInfo = this.userInfoService.getCurrent(); int uid = userInfo.getUser().getId(); String rootPath = MvcContext.getInstance().getRootPath(); String avatarPath = this.userInfoService.prepareUploadFolder(); String finalPath = rootPath + avatarPath; logger.info("上传目录:" + finalPath); File file = this.saveFile("avatar", finalPath + "/o_" + uid); logger.info("保存头像到:" + file.getAbsolutePath()); userInfo.getUser().setAvatar(avatarPath + "/" + file.getName()); this.userService.save(userInfo.getUser()); try { // 创建小、中、大头像 String extension = StringUtil.substring2(file.getName(), ".").replace(".", ""); if (StringUtil.isBlank(extension)) { extension = "png"; // 默认格式 } BufferedImage image = ImageIO.read(file); BufferedImage largeAvatar = Scalr.resize(image, 128, 128); // 大头像 ImageIO.write(largeAvatar, extension, new File(file.getAbsolutePath().replace("o_", "l_"))); BufferedImage mediumAvatar = Scalr.resize(image, 48, 48); // 中头像 ImageIO.write(mediumAvatar, extension, new File(file.getAbsolutePath().replace("o_", "m_"))); BufferedImage smallAvatar = Scalr.resize(image, 16, 16); // 小头像 ImageIO.write(smallAvatar, extension, new File(file.getAbsolutePath().replace("o_", "s_"))); } catch (IOException e) { e.printStackTrace(); } return new JsonResultView("file", avatarPath); }
private BufferedImage resizeImage(BufferedImage img) { int myheight = img.getHeight(); int mywidth = img.getWidth(); if (mywidth > m_maxsize.width || myheight > m_maxsize.height) { if (mywidth > myheight) { img = Scalr.resize(img, Scalr.Mode.FIT_TO_HEIGHT, m_maxsize.height); } else { img = Scalr.resize(img, Scalr.Mode.FIT_TO_WIDTH, m_maxsize.width); } } return img; }
private void updateSystemIcon() { Window window = getWindow(); if (window == null) { mySystemIcon = null; return; } List<Image> icons = window.getIconImages(); assert icons != null; if (icons.size() == 0) { mySystemIcon = null; } else if (icons.size() == 1) { mySystemIcon = icons.get(0); } else { final JBDimension size = JBUI.size(32); final Image image = icons.get(0); mySystemIcon = Scalr.resize( ImageUtil.toBufferedImage(image), Scalr.Method.ULTRA_QUALITY, size.width, size.height); } }
@RequestMapping( value = "/{id}/height/{height}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) public byte[] getImageWithHeight(@PathVariable int id, @PathVariable int height) throws IOException { VehicleImageRaw image = imageRepository.findOne(id); byte[] imageData = image.getImageData(); ByteArrayInputStream bais = new ByteArrayInputStream(imageData); BufferedImage bufferedImage = ImageIO.read(bais); // int width = bufferedImage.getHeight() / bufferedImage.getWidth() * height; double ratio = 1.0 * bufferedImage.getWidth() / bufferedImage.getHeight(); Double width = height * ratio; BufferedImage bufferedResizedImage = Scalr.resize( bufferedImage, Scalr.Method.BALANCED, Scalr.Mode.AUTOMATIC, width.intValue(), height); // 400,300 was the size we expected ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bufferedResizedImage, "jpg", baos); baos.flush(); return baos.toByteArray(); }
public static BufferedImage createThumbnail(BufferedImage img) { // Create quickly, then smooth and brighten it. img = org.imgscalr.Scalr.resize(img, Method.SPEED, 125, OP_ANTIALIAS, OP_BRIGHTER); // Let's add a little border before we return result. return pad(img, 4); }
@Override public Icon scale(float scaleFactor) { if (scaleFactor == 1f) { return this; } if (scaledIcons == null) { scaledIcons = new HashMap<Float, Icon>(1); } Icon result = scaledIcons.get(scaleFactor); if (result != null) { return result; } final Image image = ImageLoader.loadFromUrl(myUrl, UIUtil.isUnderDarcula(), scaleFactor >= 1.5f, filter); if (image != null) { int width = (int) (getIconWidth() * scaleFactor); int height = (int) (getIconHeight() * scaleFactor); final BufferedImage resizedImage = Scalr.resize( ImageUtil.toBufferedImage(image), Scalr.Method.ULTRA_QUALITY, width, height); result = getIcon(resizedImage); scaledIcons.put(scaleFactor, result); return result; } return this; }
private static byte[] resizeImage( BufferedImage bufferedImage, WritebleImageFormat format, int width, int height) throws IOException { BufferedImage thumbnail = Scalr.resize(bufferedImage, Scalr.Method.SPEED, Scalr.Mode.FIT_EXACT, width, height); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(thumbnail, format.name(), output); return output.toByteArray(); } // convertSizeToDimensions
public void resizeByWidth( MultipartFile multipartFile, String fileName, int maxWidth, int maxHeight) throws DdException, IOException { boolean f = false; for (String mime : mimeTypeAllow) { if (mime.equalsIgnoreCase(multipartFile.getContentType())) { f = true; break; } } if (!f) { throw new DdException( DdException.VALIDATION_EXCEPTION, UploadUtil.FILE_TYPE_NOT_ALLOW_CODE, UploadUtil.FILE_TYPE_NOT_ALLOW); } String fileNameTemp = "", fileExt = ""; fileNameTemp = multipartFile.getOriginalFilename(); if (fileNameTemp.indexOf(".") > -1) { fileExt = fileNameTemp.substring(fileNameTemp.lastIndexOf("."), fileNameTemp.length()); } fileExt = fileExt.toLowerCase(); // Check for valid file type upload file if (fileTypeAllow.indexOf(fileExt) == -1) { throw new DdException( DdException.VALIDATION_EXCEPTION, UploadUtil.FILE_TYPE_NOT_ALLOW_CODE, UploadUtil.FILE_TYPE_NOT_ALLOW); } // Check for limit upload file if (multipartFile.getSize() <= 0 || multipartFile.getSize() > fileSizeLimit) { throw new DdException( DdException.VALIDATION_EXCEPTION, UploadUtil.FILE_SIZE_LIMIT_CODE, UploadUtil.FILE_SIZE_LIMIT); } BufferedImage img = ImageIO.read(multipartFile.getInputStream()); if (img.getWidth() > maxWidth) { img = Scalr.resize( img, Scalr.Method.BALANCED, Scalr.Mode.FIT_TO_WIDTH, maxWidth, maxHeight, Scalr.OP_ANTIALIAS); } ImageIO.write(img, fileExt.substring(1), new File(path + fileName)); }
public static void resize(File file, int width, int height) throws FileOperationException { BufferedImage image; try { image = ImageIO.read(file); image = Scalr.resize(image, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT, width, height); saveToJPG(image, file); image.flush(); } catch (IOException | IllegalArgumentException e) { logger.error(e.getMessage(), e); throw new FileOperationException("Resizing failed"); } }
@NotNull private static Image scaleImage(Image image, float scale) { int w = image.getWidth(null); int h = image.getHeight(null); if (w <= 0 || h <= 0) { return image; } int width = (int) (scale * w); int height = (int) (scale * h); // Using "QUALITY" instead of "ULTRA_QUALITY" results in images that are less blurry // because ultra quality performs a few more passes when scaling, which introduces blurriness // when the scaling factor is relatively small (i.e. <= 3.0f) -- which is the case here. return Scalr.resize(ImageUtil.toBufferedImage(image), Scalr.Method.QUALITY, width, height); }
public static BufferedImage calcImage(byte[] bytes) { if (bytes == null) { return null; } BufferedImage bufferedImage = null; try { bufferedImage = ImageIO.read(new ByteArrayInputStream(bytes)); bufferedImage = Scalr.resize(bufferedImage, 20, 20); return bufferedImage; } catch (IOException e) { // todo log e.printStackTrace(); } return null; }
private ImageIcon getScaledIcon(ImageIcon original) { Canvas c = new Canvas(); FontMetrics fm = c.getFontMetrics(getFont()); int height = (int) (fm.getHeight() * 2f); int width = original.getIconWidth() / original.getIconHeight() * height; BufferedImage scaledImage = Scalr.resize( com.bric.image.ImageLoader.createImage(original.getImage()), Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, width, height, Scalr.OP_ANTIALIAS); return new ImageIcon(scaledImage); }
@Override public ProcessedImage process(ImageSubmission imageSubmission) throws Exception { final String imagePath = path + imageSubmission.getFileName(); try { final BufferedImage originalImage = ImageIO.read(new File(imagePath)); final BufferedImage resizedImage = Scalr.resize(originalImage, width, height); return new ProcessedImage(resizedImage, imageSubmission.getFileName()); } catch (Exception e) { LOG.warn( "Failed to convert " + imagePath + ", skipping - sorry submitter! (" + e.getMessage() + ")"); return null; } }
/** @param data:image/jpeg;base64, */ public String getDimAndGenerate64BaseCode( int heightL, int widthL, String type, InputStream imageStream) { String imageString = null; try { BufferedImage _image = ImageIO.read(imageStream); if (_image != null && type != null) { ByteArrayOutputStream os = null; try { int h = _image.getHeight(); int w = _image.getWidth(); if (h >= heightL && w >= widthL) { os = new ByteArrayOutputStream(); BufferedImage bImage = Scalr.resize( _image, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, 150, 120, Scalr.OP_ANTIALIAS); ImageIO.write(bImage, type, os); byte[] data = os.toByteArray(); imageString = new BASE64Encoder().encode(data); } } catch (Exception ex2) { ex2.printStackTrace(); } finally { if (os != null) { os.close(); } } } } catch (Exception e) { e.printStackTrace(); } if (imageString != null) { imageString = "data:image/" + type + ";base64," + imageString; } return imageString; }
public CA toScaledCA(float scale) { int w = _i.getWidth(); int h = _i.getHeight(); /* BufferedImage scaled = new BufferedImage((int)(w*scale), (int)(h*scale), BufferedImage.TYPE_INT_ARGB); AffineTransform at = new AffineTransform(); at.scale(scale, scale); RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); AffineTransformOp scaleOp = new AffineTransformOp(at, hints); scaled = scaleOp.filter(_i, scaled); return new CA(scaled); */ return new CA( Scalr.resize( _i, Scalr.Method.ULTRA_QUALITY, (int) (w * scale), (int) (h * scale), Scalr.OP_ANTIALIAS, Scalr.OP_BRIGHTER)); }
public void scalePicture() { if ((sourcePicture == null) || (sourcePicture.getSourceBufferedImage() == null)) { ScaleFactor = 1.0; return; } setStatus(SCALING, "Scaling picture."); BufferedImage org = sourcePicture.getSourceBufferedImage(); int w = sourcePicture.getWidth(); int h = sourcePicture.getHeight(); calcScale(); scaledPicture = Scalr.resize( org, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, (int) (ScaleFactor * w), (int) (ScaleFactor * h), Scalr.OP_ANTIALIAS); // System.out.printf("scaled=%d,%d%n", scaledPicture.getWidth(), scaledPicture.getHeight()); setStatus(READY, "Scaled Picture is ready."); }
/** * Creates a new meal * * <p>PUT-JSON object should contain user_id, name, price, servings, category, * * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Statement stmt = null; String add_meal = null; String json = null; String image = null; // establish database connection Connection conn = dao.connect(); if (req.getParameter("json") != null && !req.getParameter("json").isEmpty()) json = req.getParameter("json"); if (req.getParameter("image") != null && !req.getParameter("image").isEmpty()) image = req.getParameter("image"); JSONObject job = new JSONObject(); try { // and convert to JSON job = (JSONObject) JSONValue.parse(json); // variables representing the meal String user_id = null; String name = null; String price = null; Double meal_price = 0.0; String servings = null; Integer meal_servings = 0; String description = null; String ingredients = null; Long time = null; byte[] decodedBytes = null; byte[] imageInByte = null; byte[] middle_byte = null; InputStream in_image = null; InputStream in_thumb = null; InputStream in_image_middle = null; if (job.get("user_id") != null) user_id = (String) job.get("user_id"); if (job.get("name") != null) name = (String) job.get("name"); if (job.get("price") != null) price = (String) job.get("price"); if (job.get("servings") != null) servings = (String) job.get("servings"); if (job.get("description") != null) description = (String) job.get("description"); if (job.get("ingredients") != null) ingredients = (String) job.get("ingredients"); if (job.get("time") != null) time = (Long) job.get("time"); meal_price = Double.parseDouble(price); meal_servings = Integer.valueOf(servings); // convert image from BASE64 to normal size & thumbnail if (image != null && !image.isEmpty()) { // encode image to resize BASE64Decoder decoder = new BASE64Decoder(); decodedBytes = decoder.decodeBuffer(image); // create thumbnail; 96px,96px InputStream in = new ByteArrayInputStream(decodedBytes); BufferedImage bImageFromConvert = ImageIO.read(in); BufferedImage bImage_small = Scalr.resize(bImageFromConvert, 96); // convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bImage_small, "png", baos); baos.flush(); imageInByte = baos.toByteArray(); // create middle-sized version, width is 250px InputStream img_middle = new ByteArrayInputStream(decodedBytes); BufferedImage bImage_middle = ImageIO.read(img_middle); BufferedImage middle = Scalr.resize(bImage_middle, 250); // convert BufferedImage to byte array ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); ImageIO.write(middle, "png", baos2); baos2.flush(); middle_byte = baos2.toByteArray(); // blob-inputstreams in_thumb = new ByteArrayInputStream(imageInByte); in_image = new ByteArrayInputStream(decodedBytes); in_image_middle = new ByteArrayInputStream(middle_byte); } // create INSERT statement if (image == null) { add_meal = "INSERT INTO T_MEALS ( USER_ID, MEAL_NAME, MEAL_PRICE, MEAL_SERVINGS, MEAL_TIME, MEAL_DESCRIPTION, MEAL_INGREDIENTS ) " + "VALUES ('" + user_id + "', '" + name + "', " + meal_price + ", " + meal_servings + ", " + time + ", '" + description + "', '" + ingredients + "')"; stmt = conn.createStatement(); stmt.executeQuery(add_meal); // get the new ID of this place Long meal_id = (long) 0; PreparedStatement getMealID = conn.prepareStatement( "Select meal_id from T_MEALS where MEAL_NAME = '" + name + "' and user_id = '" + user_id + "'"); ResultSet id = getMealID.executeQuery(); if (id.next()) { if (id.getString("meal_id") != null) meal_id = (long) Integer.valueOf(id.getString("place_id")); } } else { // statements to store images and meal OraclePreparedStatement ps = (OraclePreparedStatement) conn.prepareStatement( "INSERT INTO T_MEALS ( USER_ID, MEAL_NAME, MEAL_PRICE, MEAL_SERVINGS, MEAL_TIME, MEAL_DESCRIPTION, MEAL_INGREDIENTS, THUMBNAIL ) " + "VALUES ('" + user_id + "', '" + name + "', " + meal_price + ", " + meal_servings + ", " + time + ", '" + description + "', '" + ingredients + "' , ?)"); ps.setBinaryStream(1, in_thumb, imageInByte.length); ps.executeUpdate(); // get the new ID of this place Long meal_id = (long) 0; PreparedStatement getMealID = conn.prepareStatement( "Select meal_id from T_MEALS where MEAL_NAME = '" + name + "' and user_id = '" + user_id + "'"); ResultSet id = getMealID.executeQuery(); if (id.next()) { if (id.getString("meal_id") != null) meal_id = (long) Integer.valueOf(id.getString("meal_id")); // add pictures PreparedStatement ps2 = conn.prepareStatement( "INSERT INTO T_IMAGES ( MEAL_ID, USER_ID, IMAGE, IMAGE_MIDDLE) VALUES(" + String.valueOf(meal_id) + "," + user_id + ",?,?)"); ps2.setBinaryStream(1, in_image, decodedBytes.length); ps2.setBinaryStream(2, in_image_middle, middle_byte.length); ps2.executeUpdate(); } conn.commit(); } resp.setStatus(HttpServletResponse.SC_CREATED); } catch (Exception e) { resp.setStatus(HttpServletResponse.SC_CONFLICT); e.printStackTrace(); } finally { // close connection dao.close(conn); } resp.setContentType("text/javascript"); resp.flushBuffer(); }
public void createThumbnail(MultipartFile multipartFile, String fileName, int thumbnailSize) throws DdException, IOException { boolean f = false; for (String mime : mimeTypeAllow) { if (mime.equalsIgnoreCase(multipartFile.getContentType())) { f = true; break; } } if (!f) { throw new DdException( DdException.VALIDATION_EXCEPTION, UploadUtil.FILE_TYPE_NOT_ALLOW_CODE, UploadUtil.FILE_TYPE_NOT_ALLOW); } String fileNameTemp = "", fileExt = ""; fileNameTemp = multipartFile.getOriginalFilename(); if (fileNameTemp.indexOf(".") > -1) { fileExt = fileNameTemp.substring(fileNameTemp.lastIndexOf("."), fileNameTemp.length()); } fileExt = fileExt.toLowerCase(); // Check for valid file type upload file if (fileTypeAllow.indexOf(fileExt) == -1) { throw new DdException( DdException.VALIDATION_EXCEPTION, UploadUtil.FILE_TYPE_NOT_ALLOW_CODE, UploadUtil.FILE_TYPE_NOT_ALLOW); } // Check for limit upload file if (multipartFile.getSize() <= 0 || multipartFile.getSize() > fileSizeLimit) { throw new DdException( DdException.VALIDATION_EXCEPTION, UploadUtil.FILE_SIZE_LIMIT_CODE, UploadUtil.FILE_SIZE_LIMIT); } BufferedImage img = ImageIO.read(multipartFile.getInputStream()); int cropMargin = (int) Math.abs(Math.round(((img.getWidth() - img.getHeight()) / 2.0))); // determine the crop coordinates int x1 = 0; int y1 = 0; int width = img.getWidth(); int height = img.getHeight(); if (img.getWidth() > img.getHeight()) { x1 = cropMargin; width = height; } else { y1 = cropMargin; height = width; } BufferedImage thumbnail = Scalr.crop(img, x1, y1, width, height); thumbnail = Scalr.resize( thumbnail, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.AUTOMATIC, thumbnailSize, thumbnailSize, Scalr.OP_ANTIALIAS); ImageIO.write(thumbnail, fileExt.substring(1), new File(path + fileName)); }