org.imgscalr.Scalr Java Examples

The following examples show how to use org.imgscalr.Scalr. 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: ImageService.java    From htwplus with MIT License 8 votes vote down vote up
static public 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");
    }
}
 
Example #2
Source File: ImageLoader.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Image scaleImage(Image image, double scale) {
  if (scale == 1.0) return image;

  if (image instanceof JBHiDPIScaledImage) {
    return ((JBHiDPIScaledImage)image).scale(scale);
  }
  int w = image.getWidth(null);
  int h = image.getHeight(null);
  if (w <= 0 || h <= 0) {
    return image;
  }
  int width = (int)Math.round(scale * w);
  int height = (int)Math.round(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, Scalr.Mode.FIT_EXACT, width, height, (BufferedImageOp[])null);
}
 
Example #3
Source File: ActionImageBase64Encode.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
protected ActionResult<WrapOutString> execute( HttpServletRequest request, EffectivePerson effectivePerson, 
		Integer size, byte[] bytes, FormDataContentDisposition disposition) {
	ActionResult<WrapOutString> result = new ActionResult<>();
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	
	try ( InputStream input = new ByteArrayInputStream(bytes)) {
		BufferedImage image = ImageIO.read(input);
		int width = image.getWidth();
		int height = image.getHeight();
		if (size > 0) {
			if (width * height > size * size) {
				image = Scalr.resize(image, size);
			}
		}
		ImageIO.write(image, "png", baos);
		byte[] byteArray = baos.toByteArray();
		WrapOutString wrap = new WrapOutString();
		wrap.setValue(Base64.encodeBase64String(byteArray));
		result.setData( wrap);
	} catch (IOException e) {
		e.printStackTrace();
		result.error(e);
	}
	return result;
}
 
Example #4
Source File: ContentServiceImpl.java    From hermes with Apache License 2.0 6 votes vote down vote up
/**
 * 图文信息中超过 预设宽度的图片 压缩
 * 
 * @param originBase64
 * @param maxWidth
 * @return
 * @throws Exception
 */
public String compressImgToBase64(String originBase64, int maxWidth) throws Exception {
	if (Strings.empty(originBase64)) {
		return null;
	}
	// Base64解码
	byte[] originBinary = Base64.decodeBase64(originBase64);
	for (int i = 0; i < originBinary.length; ++i) {
		if (originBinary[i] < 0) {// 调整异常数据
			originBinary[i] += 256;
		}
	}
	BufferedImage source = ImageIO.read(new ByteArrayInputStream(originBinary));
	int ogriWidth = source.getWidth();
	if (ogriWidth > maxWidth) {
		source = Scalr.resize(source, maxWidth); // 只设置宽度
	} else {
		return null;
	}
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	ImageIO.write(source, "jpeg", os);
	os.flush();
	byte[] newBytes = os.toByteArray();
	os.close();
	return  Base64.encodeBase64String(newBytes);
}
 
Example #5
Source File: ReportContext.java    From carina with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        if (width > 0 && height > 0) {
            BufferedImage resizedImage = Scalr.resize(image, Scalr.Method.BALANCED, Scalr.Mode.FIT_TO_WIDTH, width, height,
                    Scalr.OP_ANTIALIAS);
            if (resizedImage.getHeight() > height) {
                resizedImage = Scalr.crop(resizedImage, resizedImage.getWidth(), height);
            }
            ImageIO.write(resizedImage, "PNG", new File(path));
        } else {
            ImageIO.write(image, "PNG", new File(path));
        }

    } catch (Exception e) {
        LOGGER.error("Unable to save screenshot: " + e.getMessage());
    }
}
 
Example #6
Source File: JBHiDPIScaledImage.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Returns JBHiDPIScaledImage of the same structure scaled by the provided factor.
 *
 * @param scaleFactor the scale factor
 * @return scaled instance
 */
@Nonnull
public JBHiDPIScaledImage scale(double scaleFactor) {
  Image img = myImage == null ? this : myImage;

  int w = (int)(scaleFactor * getRealWidth(null));
  int h = (int)(scaleFactor * getRealHeight(null));
  if (w <= 0 || h <= 0) return this;

  Image scaled = Scalr.resize(ImageUtil.toBufferedImage(img), Scalr.Method.QUALITY, w, h);

  double newUserWidth = w / myScale;
  double newUserHeight = h / myScale;

  if (myImage != null) {
    return new JBHiDPIScaledImage(scaled, newUserWidth, newUserHeight, getType());
  }
  JBHiDPIScaledImage newImg = new JBHiDPIScaledImage(myScale, newUserWidth, newUserHeight, getType(), RoundingMode.ROUND);
  Graphics2D g = newImg.createGraphics();
  g.drawImage(scaled, 0, 0, (int)round(newUserWidth), (int)round(newUserHeight), 0, 0, scaled.getWidth(null), scaled.getHeight(null), null);
  g.dispose();
  return newImg;
}
 
Example #7
Source File: AdrCapturePanel.java    From MercuryTrade with MIT License 6 votes vote down vote up
@Override
public void onViewInit() {
    this.setLayout(new GridLayout(1, 1));
    this.setPreferredSize(this.descriptor.getSize());
    this.captureLabel = new JLabel();
    this.setBackground(AppThemeColor.ADR_CAPTURE_BG);
    this.setBorder(BorderFactory.createLineBorder(AppThemeColor.BORDER, 1));
    this.progressTl = new Timeline(this);
    this.progressTl.addPropertyToInterpolate("captureCount", 0, this.descriptor.getFps());
    this.captureLabel.setIcon(new ImageIcon(Scalr.resize(getCapture(), descriptor.getSize().width, descriptor.getSize().height)));
    this.progressTl.addCallback(new TimelineCallbackAdapter() {
        @Override
        public void onTimelineStateChanged(Timeline.TimelineState oldState, Timeline.TimelineState newState, float durationFraction, float timelinePosition) {
            captureLabel.setIcon(new ImageIcon(Scalr.resize(getCapture(), descriptor.getSize().width, descriptor.getSize().height)));
        }
    });
    this.progressTl.setDuration(1000 / this.descriptor.getFps());

    this.add(this.captureLabel);
    MercuryStoreUI.adrRepaintSubject.onNext(true);
}
 
Example #8
Source File: PdfPanel.java    From swift-explorer with Apache License 2.0 6 votes vote down vote up
private BufferedImage getBestFit (BufferedImage bi, int maxWidth, int maxHeight)
  {
if (bi == null)
	return null ;

  	Mode mode = Mode.AUTOMATIC ;
  	int maxSize = Math.min(maxWidth, maxHeight) ;
  	double dh = (double)bi.getHeight() ;
  	if (dh > Double.MIN_VALUE)
  	{
  		double imageAspectRatio = (double)bi.getWidth() / dh ;
      	if (maxHeight * imageAspectRatio <=  maxWidth)
      	{
      		maxSize = maxHeight ;
      		mode = Mode.FIT_TO_HEIGHT ;
      	}
      	else
      	{
      		maxSize = maxWidth ;
      		mode = Mode.FIT_TO_WIDTH ;
      	}	
  	}
  	return Scalr.resize(bi, Method.QUALITY, mode, maxSize, Scalr.OP_ANTIALIAS) ; 
  }
 
Example #9
Source File: ImageUtil.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
synchronized public static void resize(String filename, InputStream orig, OutputStream dest, int width, int height) throws IOException {
	if (width > 0 || height > 0) {

		String formatName = getFormatName(filename);

		Mode mode = Mode.AUTOMATIC;
		if (height == 0)
			mode = Mode.FIT_TO_WIDTH;
		else if (width == 0)
			mode = Mode.FIT_TO_HEIGHT;

		BufferedImage src = ImageIO.read(orig);
		BufferedImage thumbnail = null;
		if (src.getHeight() < height && src.getWidth() < width) {
			thumbnail = src;
		} else {
			thumbnail = Scalr.resize(src, Method.ULTRA_QUALITY, mode, width, height);
		}
		if (!ImageIO.write(thumbnail, formatName, dest)) {
			throw new IOException("ImageIO.write error");
		}
	}
}
 
Example #10
Source File: ImageUtil.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param buffImage
 * @param scaleWidth
 * @param scaleHeight
 * @return
 */
public static BufferedImage scaleImage(BufferedImage buffImage, int scaleWidth, int scaleHeight) {
    int imgHeight = buffImage.getHeight();
    int imgWidth = buffImage.getWidth();

    float destHeight = scaleHeight;
    float destWidth = scaleWidth;

    if ((imgWidth >= imgHeight) && (imgWidth > scaleWidth)) {
        destHeight = imgHeight * ((float) scaleWidth / imgWidth);
    } else if ((imgWidth < imgHeight) && (imgHeight > scaleHeight)) {
        destWidth = imgWidth * ((float) scaleHeight / imgHeight);
    } else {
        return buffImage;
    }

    return Scalr.resize(buffImage, Method.BALANCED, Mode.AUTOMATIC, (int) destWidth, (int) destHeight);
}
 
Example #11
Source File: ImageUtil.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
public static BufferedImage generateImageThumbnail(InputStream imageStream) throws IOException {
    try {
        int idealWidth = 256;
        BufferedImage source = ImageIO.read(imageStream);
        if (source == null) {
            return null;
        }
        int imgHeight = source.getHeight();
        int imgWidth = source.getWidth();

        float scale = (float) imgWidth / idealWidth;
        int height = (int) (imgHeight / scale);

        BufferedImage rescaledImage = Scalr.resize(source, Method.QUALITY,
                Mode.AUTOMATIC, idealWidth, height);
        if (height > 400) {
            rescaledImage = rescaledImage.getSubimage(0, 0,
                    Math.min(256, rescaledImage.getWidth()), 400);
        }
        return rescaledImage;
    } catch (Exception e) {
        LOG.error("Generate thumbnail for error", e);
        return null;
    }
}
 
Example #12
Source File: ProfileUtils.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Scale an image so it is fit within a give width and height, whilst maintaining its original proportions 
 *
 * @param imageData		bytes of the original image
 * @param maxSize		maximum dimension in px
 */
public static byte[] scaleImage(InputStream in, int maxSize, String mimeType) {
	
	byte[] scaledImageBytes = null;
	try {
		//convert original image to inputstream
		
		//original buffered image
		BufferedImage originalImage = ImageIO.read(in);
		
		//scale the image using the imgscalr library
		BufferedImage scaledImage = Scalr.resize(originalImage, maxSize);
		
		//convert BufferedImage to byte array
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos);
		baos.flush();
		scaledImageBytes = baos.toByteArray();
		baos.close();
		
	} catch (Exception e) {
		log.error("Scaling image failed.", e);
	}
	
	return scaledImageBytes;
}
 
Example #13
Source File: ImageEditService.java    From zhcet-web with Apache License 2.0 6 votes vote down vote up
private byte[] generateThumbnail(BufferedImage image, String format, int pixels) throws IOException {
    log.debug("Original Image Resolution : {}x{}", image.getHeight(), image.getWidth());

    BufferedImage newImage = null;
    if (Math.max(image.getHeight(), image.getWidth()) > pixels) {
        log.debug("Image larger than {} pixels. Resizing...", pixels);
        Scalr.Mode mode = image.getHeight() > image.getWidth() ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
        newImage = Scalr.resize(image, Scalr.Method.ULTRA_QUALITY, mode, pixels, pixels);
        log.debug("New Image Resolution : {}x{}", newImage.getHeight(), newImage.getWidth());
    }

    newImage = crop(newImage, pixels);
    if (newImage == null)
        newImage = crop(image, pixels);

    if (newImage == null)
        return null;

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.write(newImage, format, os);
    return os.toByteArray();
}
 
Example #14
Source File: FileUploadApiController.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
private UploadBase64FileModification resize(UploadBase64FileModification upload, MimeType mimeType) throws IOException {
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(upload.getFile()));
    //resize only if the image is bigger than 500px on one of the side
    if(image.getWidth() > IMAGE_THUMB_MAX_WIDTH_PX || image.getHeight() > IMAGE_THUMB_MAX_HEIGHT_PX) {
        UploadBase64FileModification resized = new UploadBase64FileModification();
        BufferedImage thumbImg = Scalr.resize(image, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, IMAGE_THUMB_MAX_WIDTH_PX, IMAGE_THUMB_MAX_HEIGHT_PX, Scalr.OP_ANTIALIAS);
        try (final var baos = new ByteArrayOutputStream()) {
            ImageIO.write(thumbImg, mimeType.getSubtype(), baos);
            resized.setFile(baos.toByteArray());
        }
        resized.setAttributes(upload.getAttributes());
        resized.setName(upload.getName());
        resized.setType(upload.getType());
        return resized;
    }
    return upload;
}
 
Example #15
Source File: Photograph.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static byte[] processImage(BufferedImage image, int xRatio, int yRatio, int width, int height, PictureMode pictureMode) {
    final BufferedImage transformed, scaled;
    switch (pictureMode) {
    case FIT:
        transformed = Picture.transformFit(image, xRatio, yRatio);
        break;
    case ZOOM:
        transformed = Picture.transformZoom(image, xRatio, yRatio);
        break;
    default:
        transformed = Picture.transformFit(image, xRatio, yRatio);
        break;
    }
    scaled = Scalr.resize(transformed, Method.QUALITY, Mode.FIT_EXACT, width, height);
    return Picture.writeImage(scaled, ContentType.PNG);
}
 
Example #16
Source File: ProfileUtils.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Scale an image so it is fit within a give width and height, whilst maintaining its original proportions 
 *
 * @param imageData		bytes of the original image
 * @param maxSize		maximum dimension in px
 */
public static byte[] scaleImage(InputStream in, int maxSize, String mimeType) {
	
	byte[] scaledImageBytes = null;
	try {
		//convert original image to inputstream
		
		//original buffered image
		BufferedImage originalImage = ImageIO.read(in);
		
		//scale the image using the imgscalr library
		BufferedImage scaledImage = Scalr.resize(originalImage, maxSize);
		
		//convert BufferedImage to byte array
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos);
		baos.flush();
		scaledImageBytes = baos.toByteArray();
		baos.close();
		
	} catch (Exception e) {
		log.error("Scaling image failed.", e);
	}
	
	return scaledImageBytes;
}
 
Example #17
Source File: ImageProcessor.java    From spring-batch-performance-tuning with Apache License 2.0 5 votes vote down vote up
@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;
	}
}
 
Example #18
Source File: ImageUtil.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param buffImage
 * @param percenScale
 * @return
 */
public static BufferedImage scaleImage(BufferedImage buffImage, float percenScale) {
    float width = buffImage.getWidth() * percenScale;
    float height = buffImage.getHeight() * percenScale;
    return Scalr.resize(buffImage, Method.BALANCED,
            Mode.AUTOMATIC, (int) width, (int) height);
}
 
Example #19
Source File: ImageProcessor.java    From spring-batch-performance-tuning with Apache License 2.0 5 votes vote down vote up
@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;
	}
}
 
Example #20
Source File: PassKitManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
private static byte[] scaleLogo(BufferedImage sourceImage, int factor) throws IOException {
    // base image is 160 x 50 points.
    // On retina displays, a point can be two or three pixels, depending on the device model
    int finalWidth = 160 * factor;
    int finalHeight = 50 * factor;
    var thumbImg = Scalr.resize(sourceImage, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, finalWidth, finalHeight, Scalr.OP_ANTIALIAS);
    var outputStream = new ByteArrayOutputStream();
    ImageIO.write(thumbImg, "png", outputStream);
    return outputStream.toByteArray();
}
 
Example #21
Source File: ImageProcessor.java    From spring-batch-performance-tuning with Apache License 2.0 5 votes vote down vote up
@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;
	}
}
 
Example #22
Source File: ImageProcessor.java    From spring-batch-performance-tuning with Apache License 2.0 5 votes vote down vote up
@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;
	}
}
 
Example #23
Source File: ImageService.java    From htwplus with MIT License 5 votes vote down vote up
static public void crop(File file, int x, int y, int width, int height) throws FileOperationException {
    BufferedImage image;
    try {
        image = ImageIO.read(file);
        image = Scalr.crop(image, x, y, width, height);
        saveToJPG(image, file);
        image.flush();
    } catch (IOException | IllegalArgumentException e){
        logger.error(e.getMessage(), e);
        throw new FileOperationException("Cropping failed");
    }
}
 
Example #24
Source File: ComponentsFactory.java    From MercuryTrade with MIT License 5 votes vote down vote up
public ImageIcon getIcon(URL iconPath, float size) {
    BufferedImage icon = null;
    try {
        BufferedImage buttonIcon = ImageIO.read(iconPath);
        icon = Scalr.resize(buttonIcon, (int) (scale * size));
    } catch (IOException e) {
        log.error(e);
    }
    return new ImageIcon(icon);
}
 
Example #25
Source File: ComponentsFactory.java    From MercuryTrade with MIT License 5 votes vote down vote up
public ImageIcon getIcon(String iconPath, float size) {
    BufferedImage icon = null;
    try {
        BufferedImage buttonIcon = ImageIO.read(getClass().getClassLoader().getResource(iconPath));
        icon = Scalr.resize(buttonIcon, (int) (scale * size));
    } catch (IOException e) {
        log.error(e);
    }
    return new ImageIcon(icon);
}
 
Example #26
Source File: MercuryAppLoadingUI.java    From MercuryTrade with MIT License 5 votes vote down vote up
public ImageIcon getIcon(String iconPath, int size) {
    BufferedImage icon = null;
    try {
        BufferedImage buttonIcon = ImageIO.read(getClass().getClassLoader().getResource(iconPath));
        icon = Scalr.resize(buttonIcon, size);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new ImageIcon(icon);
}
 
Example #27
Source File: ProgressiveAlgorithm.java    From density-converter with Apache License 2.0 5 votes vote down vote up
@Override
public BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight) {
    switch (type) {
        case NOBEL_BILINEAR:
            return new MultiStepRescaleOp(dWidth, dHeight, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
                    .filter(imageToScale, null);
        case NOBEL_BICUBUC:
            return new MultiStepRescaleOp(dWidth, dHeight, RenderingHints.VALUE_INTERPOLATION_BICUBIC)
                    .filter(imageToScale, null);
        case NOBEL_NEAREST_NEIGHBOR:
            return new MultiStepRescaleOp(dWidth, dHeight, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR)
                    .filter(imageToScale, null);
        case NOBEL_LANCZOS3:
            return new MultiStepLanczos3RescaleOp(dWidth, dHeight).filter(imageToScale, null);
        case PROGRESSIVE_BILINEAR_AND_LANCZOS2:
            return scaleProgressiveLanczos(imageToScale, dWidth, dHeight, 2);
        case PROGRESSIVE_BILINEAR_AND_LANCZOS3:
            return scaleProgressiveLanczos(imageToScale, dWidth, dHeight, 3);
        case THUMBNAILATOR_BILINEAR:
            return new ThumbnailnatorProgressiveAlgorithm(RenderingHints.VALUE_INTERPOLATION_BILINEAR).scale(imageToScale, dWidth, dHeight);
        case THUMBNAILATOR_BICUBUC:
            return new ThumbnailnatorProgressiveAlgorithm(RenderingHints.VALUE_INTERPOLATION_BICUBIC).scale(imageToScale, dWidth, dHeight);
        case IMGSCALR_SEVENTH_STEP:
            return Scalr.resize(imageToScale, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT, dWidth, dHeight, null);
        case IMGSCALR_HALF_STEP:
            return Scalr.resize(imageToScale, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, dWidth, dHeight, null);
        default:
            throw new IllegalArgumentException("unknown algorithm");
    }
}
 
Example #28
Source File: ImgscalrImageScaler.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
protected static Scalr.Method getFilter(Map<String, Object> options) throws IllegalArgumentException {
    Object filterObj = options.get("filter");
    if (filterObj == null) return null;
    else if (filterObj instanceof Scalr.Method) return (Scalr.Method) filterObj;
    else {
        String filterName = (String) filterObj;
        if (filterName.isEmpty()) return null;
        if (!filterMap.containsKey(filterName)) throw new IllegalArgumentException("filter '" + filterName + "' not supported by " + API_NAME + " library");
        return filterMap.get(filterName);
    }
}
 
Example #29
Source File: ImageScalarImpl.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void scale(Resource resource, ImageSize size, Path targetPath) {
    try (InputStream inputStream = resource.openStream()) {
        BufferedImage image = ImageIO.read(inputStream);
        int targetHeight = size.height;
        int targetWidth = size.width;

        if (targetHeight == 0) {
            targetHeight = size.width * image.getHeight() / image.getWidth();
        }

        BufferedImage chopped = chop(image, targetWidth, targetHeight);
        BufferedImage resized = Scalr.resize(chopped, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT,
            targetWidth, targetHeight, Scalr.OP_ANTIALIAS);

        String fileExtension = Files.getFileExtension(resource.path());
        OutputStream out = new FileOutputStream(targetPath.toFile());
        if (isJGP(fileExtension)) {
            writeJPG(resized, out, 0.75);
        } else {
            ImageIO.write(resized, fileExtension, out);
        }
        out.close();
    } catch (IOException e) {
        throw new ApplicationException(e);
    }
}
 
Example #30
Source File: Screenshot.java    From carina with Apache License 2.0 5 votes vote down vote up
/**
 * Resizes image according to specified dimensions.
 *
 * @param bufferedImage
 *            - image to resize.
 * @param width
 *            - new image width.
 * @param height
 *            - new image height.
 * @param path
 *            - path to screenshot file.
 */
private static void resizeImg(BufferedImage bufferedImage, int width, int height, String path) {
    try {
        BufferedImage bufImage = Scalr.resize(bufferedImage, Scalr.Method.BALANCED, Scalr.Mode.FIT_TO_WIDTH, width, height,
                Scalr.OP_ANTIALIAS);
        if (bufImage.getHeight() > height) {
            bufImage = Scalr.crop(bufImage, bufImage.getWidth(), height);
        }
        ImageIO.write(bufImage, "png", new File(path));
    } catch (Exception e) {
        LOGGER.error("Image scaling problem!", e);
    }
}