Example usage for java.awt Image SCALE_SMOOTH

List of usage examples for java.awt Image SCALE_SMOOTH

Introduction

In this page you can find the example usage for java.awt Image SCALE_SMOOTH.

Prototype

int SCALE_SMOOTH

To view the source code for java.awt Image SCALE_SMOOTH.

Click Source Link

Document

Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.

Usage

From source file:org.yes.cart.service.domain.impl.ImageServiceImpl.java

/**
 * {@inheritDoc}/*from  w  w  w .  j  a v  a2s.  c om*/
 */
public byte[] resizeImage(final String filename, final byte[] content, final String width, final String height,
        final boolean cropToFit) {

    try {

        final InputStream bis = new ByteArrayInputStream(content);

        final BufferedImage originalImg = ImageIO.read(bis);
        final String codec = getCodecFromFilename(filename);
        final boolean supportsAlpha = hasAlphaSupport(codec);

        int x = NumberUtils.toInt(width);
        int y = NumberUtils.toInt(height);
        int originalX = originalImg.getWidth();
        int originalY = originalImg.getHeight();

        boolean doCropToFit = cropToFit || x < forceCropToFitOnSize || y < forceCropToFitOnSize;

        final int imageType = originalImg.getType();

        final Image resizedImg;
        //            final BufferedImage resizedImg;
        final int padX, padY;
        if (doCropToFit) {
            // crop the original to best fit of target size
            int[] cropDims = cropImageToCenter(x, y, originalX, originalY);
            padX = 0;
            padY = 0;

            final BufferedImage croppedImg = originalImg.getSubimage(cropDims[0], cropDims[1], cropDims[2],
                    cropDims[3]);
            resizedImg = croppedImg.getScaledInstance(x, y, Image.SCALE_SMOOTH);

            //                final BufferedImage croppedImg = originalImg.getSubimage(cropDims[0], cropDims[1], cropDims[2], cropDims[3]);
            //                resizedImg = new BufferedImage(y, x, imageType);
            //                Graphics2D graphics = resizedImg.createGraphics();
            //                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            //                graphics.drawImage(croppedImg, 0, 0, x, y, null);
        } else {
            int[] scaleDims = scaleImageToCenter(x, y, originalX, originalY);
            padX = scaleDims[0];
            padY = scaleDims[1];

            resizedImg = originalImg.getScaledInstance(scaleDims[2], scaleDims[3], Image.SCALE_SMOOTH);

            //                resizedImg = new BufferedImage(scaleDims[3], scaleDims[2], imageType);
            //                Graphics2D graphics = resizedImg.createGraphics();
            //                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            //                graphics.drawImage(originalImg, 0, 0, scaleDims[2], scaleDims[3], null);
        }

        // base canvas
        final BufferedImage resizedImgFinal = new BufferedImage(x, y, imageType);

        // fill base color
        final Graphics2D graphics = resizedImgFinal.createGraphics();
        graphics.setPaint(supportsAlpha ? alphaBorder : defaultBorder);
        graphics.fillRect(0, 0, x, y);

        // insert scaled image
        graphics.drawImage(resizedImg, padX, padY, null);

        final ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ImageIO.write(resizedImgFinal, codec, bos);

        return bos.toByteArray();

    } catch (Exception exp) {
        ShopCodeContext.getLog(this).error("Unable to resize image " + filename, exp);
    }

    return new byte[0];

}

From source file:org.mbari.aved.ui.classifier.ClassModelListRenderer.java

public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
        boolean cellHasFocus) {
    if (isSelected) {
        setBackground(list.getSelectionBackground());
        setForeground(list.getSelectionForeground());
    } else {//ww w  .  j a  v a  2  s . c o  m
        setBackground(list.getBackground());
        setForeground(list.getForeground());
    }

    // Set the icon and text.  If icon was null, say so.
    if ((value != null) && value.getClass().equals(ClassModel.class)) {
        ClassModel model = (ClassModel) value;
        URL imageUrl = null;

        if (model != null) {
            ArrayList<String> listing = model.getRawImageFileListing();

            if (listing.size() > 0) {
                try {
                    imageUrl = new URL(
                            "file://" + model.getRawImageDirectory().toString() + "/" + listing.get(0));
                    icon = createImageIcon(imageUrl);
                } catch (MalformedURLException ex) {
                    Logger.getLogger(ClassModelListRenderer.class.getName()).log(Level.SEVERE,
                            "Error creating image icon for " + imageUrl.getFile(), ex);
                }

            } else {

                // Insert a default icon here
                URL url = Application.class.getResource("/org/mbari/aved/ui/images/missingframeexception.jpg");

                icon = new ImageIcon(url);
            }

            // scale icons to a normalized size here
            if (icon != null) {
                Image image = icon.getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH);

                icon = convertImageIcon(image, model.getColorSpace());
            }

            String name = model.getName();

            setIcon(icon);

            if (icon != null) {
                setText(name);
                setFont(list.getFont());
            } else {
                setDefaultText(name + " (no image available)", list.getFont());
            }
        }
    }

    return this;
}

From source file:common.utils.ImageUtils.java

/**
  * resize input image to new dinesions(only smaller) into rez parameter
  * @param image input image for scaling
 * @param rez resulting image. must have required width and height
 * @throws IOException//from   w w w.  j a  v a2s .  c o m
  */
public static void getScaledImageDimmension(BufferedImage image, BufferedImage rez) throws IOException {
    Graphics2D g2 = rez.createGraphics();
    if (rez.getHeight() > image.getHeight() || rez.getWidth() > image.getWidth()) {
        //rez image is bigger no resize
        g2.drawImage(image, 0, 0, null);
        return;
    }
    //1-st getting first side to resize (width or height)
    double scale_factor;
    if (getScaling(image.getHeight(), rez.getHeight()) > getScaling(image.getWidth(), rez.getWidth())) {
        //resize height
        scale_factor = getScaling(image.getHeight(), rez.getHeight());
        int width = (int) (scale_factor * image.getWidth());
        //cut width
        int x = (rez.getWidth() - width) / 2;
        g2.drawImage(image.getScaledInstance(width, rez.getHeight(), Image.SCALE_SMOOTH), x, 0, null);
        //System.out.println("resizing height: h="+image.getHeight()+"/"+rez.getHeight()+"; x="+x);
    } else {
        //resize width
        scale_factor = getScaling(image.getWidth(), rez.getWidth());
        int height = (int) (scale_factor * image.getHeight());
        //cut height
        int y = (rez.getHeight() - height) / 2;
        g2.drawImage(image.getScaledInstance(rez.getWidth(), height, Image.SCALE_SMOOTH), 0, y, null);
        //System.out.println("resizing width: w="+image.getWidth()+"/"+rez.getWidth()+"; y="+y);
    }
    g2.dispose();
}

From source file:ru.codemine.pos.ui.windows.products.ProductWindow.java

@Override
public void showWindow(Product product) {
    if (!actionListenersInit)
        setupActionListeners();/*from  ww w  .  j  a  v  a 2s  . c  om*/

    this.product = product;

    setTitle(" - " + product.getName());

    idField.setText(product.getId() == null ? "" : product.getId().toString());
    artikulField.setText(product.getArtikul());
    nameField.setText(product.getName());
    barcodeField.setText(product.getBarcode());
    priceField.setValue(product.getPrice());

    if (product.getId() == null) {
        artikulField.setEditable(true);
    } else {
        artikulField.setEditable(false);
    }

    List<Store> proxedStores = storeService.getAll();
    List<Store> stores = new ArrayList<>();
    for (Store s : proxedStores) {
        stores.add(storeService.unproxyStocks(s));
    }
    stocksTable.setModel(new ProductByStoresTableModel(product, stores));

    TableColumnModel columnModel = stocksTable.getColumnModel();
    columnModel.getColumn(0).setMaxWidth(10);

    File imgFile = new File("images/products/" + product.getArtikul() + ".jpg");
    String imgPath = "images/products/default.jpg";

    if (imgFile.exists() && !imgFile.isDirectory()) {
        imgPath = imgFile.getAbsolutePath();
    }

    ImageIcon ico = new ImageIcon(imgPath);
    if (ico.getIconHeight() > 0) {
        Image img = ico.getImage().getScaledInstance(200, 200, Image.SCALE_SMOOTH);
        imagePanel.setImage(img, true);
    }

    setVisible(true);
}

From source file:org.spoutcraft.launcher.technic.skin.ModpackSelector.java

public void redraw(PackInfo selected, boolean force) {
    // Determine if the pack is custom
    boolean custom = Settings.isPackCustom(selected.getName());

    // Set the background image based on the pack
    frame.getBackgroundImage().changeBackground(selected.getName(), new ImageIcon(selected.getBackground()),
            force);//from www .j av a2 s  .c  o  m

    // Set the icon image based on the pack
    frame.setIconImage(selected.getIcon());

    // Set the frame title based on the pack
    frame.setTitle(selected.getDisplayName());

    // Set the big button image in the middle
    buttons.get(3).setIcon(
            new ImageIcon(selected.getLogo().getScaledInstance(bigWidth, bigHeight, Image.SCALE_SMOOTH)));
    buttons.get(3).getJLabel().setVisible(selected.isLoading());

    // Set the URL for the platform button
    String url = "http://www.technicpack.net/modpack/details/" + selected.getName();
    if (selected instanceof RestInfo && !custom) {
        String newUrl = ((RestInfo) selected).getWebURL();
        if (newUrl != null && !newUrl.isEmpty()) {
            url = newUrl;
            frame.enableComponent(frame.getPlatform(), true);
        } else {
            frame.enableComponent(frame.getPlatform(), false);
        }
    }
    frame.getPlatform().setURL(url);

    // Add the first 3 buttons to the left
    for (int i = 0; i < 3; i++) {
        PackInfo pack = packs.getPrevious(i + 1);
        buttons.get(i).setIcon(
                new ImageIcon(pack.getLogo().getScaledInstance(smallWidth, smallHeight, Image.SCALE_SMOOTH)));
        buttons.get(i).getJLabel().setVisible(pack.isLoading());
    }

    // Add the last 3 buttons to the right
    for (int i = 4; i < 7; i++) {
        PackInfo pack = packs.getNext(i - 3);
        buttons.get(i).setIcon(
                new ImageIcon(pack.getLogo().getScaledInstance(smallWidth, smallHeight, Image.SCALE_SMOOTH)));
        buttons.get(i).getJLabel().setVisible(pack.isLoading());
    }

    if (selected instanceof AddPack) {
        frame.enableComponent(frame.getPackOptionsBtn(), false);
        frame.enableComponent(frame.getPackRemoveBtn(), false);
        frame.enableComponent(frame.getCustomName(), false);
        frame.enableComponent(frame.getPlatform(), false);
    } else if (custom) {
        if (selected.getLogoURL().equals("") && !selected.isLoading()) {
            buttons.get(3).getJLabel().setText(selected.getDisplayName());
            buttons.get(3).getJLabel().setVisible(true);
        }
        frame.enableComponent(frame.getPackOptionsBtn(), true);
        frame.enableComponent(frame.getPackRemoveBtn(), true);
        frame.enableComponent(frame.getPlatform(), true);
    } else {
        frame.enableComponent(frame.getPackOptionsBtn(), true);
        frame.enableComponent(frame.getPackRemoveBtn(), false);
        frame.enableComponent(frame.getCustomName(), false);
    }

    this.repaint();
}

From source file:org.shredzone.cilla.admin.AbstractImageBean.java

/**
 * Scales a {@link BufferedImage} to the given size, keeping the aspect ratio. If the
 * image is smaller than the resulting size, it will be magnified.
 *
 * @param image//from   w w w. ja  v  a 2s  . c o  m
 *            {@link BufferedImage} to scale
 * @param width
 *            Maximum result width
 * @param height
 *            Maximum result height
 * @return {@link BufferedImage} with the scaled image
 */
private BufferedImage scale(BufferedImage image, int width, int height) {
    ImageObserver observer = null;

    Image scaled = null;
    if (image.getWidth() > image.getHeight()) {
        scaled = image.getScaledInstance(width, -1, Image.SCALE_SMOOTH);
    } else {
        scaled = image.getScaledInstance(-1, height, Image.SCALE_SMOOTH);
    }

    BufferedImage result = new BufferedImage(scaled.getWidth(observer), scaled.getHeight(observer),
            BufferedImage.TYPE_INT_RGB);
    result.createGraphics().drawImage(scaled, 0, 0, observer);
    return result;
}

From source file:com.shending.support.CompressPic.java

/**
 * ?//from www  .  j  av a2  s.c o m
 *
 * @param srcFile
 * @param dstFile
 * @param widthRange
 * @param heightRange
 */
public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width,
        int height) {
    int x = 0;
    int y = 0;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
        Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
        ImageReader reader = (ImageReader) iterator.next();
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int oldWidth = reader.getWidth(0);
        int oldHeight = reader.getHeight(0);
        int newWidth, newHeight;
        if (width <= oldWidth && height <= oldHeight) {
            newWidth = oldHeight * widthRange / heightRange;
            if (newWidth < oldWidth) {
                newHeight = oldHeight;
                x = (oldWidth - newWidth) / 2;
            } else {
                newWidth = oldWidth;
                newHeight = oldWidth * heightRange / widthRange;
                y = (oldHeight - newHeight) / 2;
            }
            Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight);
            param.setSourceRegion(rectangle);
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        } else {
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = tag.createGraphics();
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight());
            g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH),
                    (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null);
            g2d.dispose();
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.notebook.gui.MainFrame.java

private Image appIcon16() {
    return appIcon().getScaledInstance(16, 16, Image.SCALE_SMOOTH);
}

From source file:org.forumj.web.servlet.post.SetAvatar.java

private String createOriginalImage(Image image, Long photoId, String fileExtention, ImageSize imageSize)
        throws IOException {
    return createImage(image, photoId, fileExtention, Image.SCALE_SMOOTH, imageSize,
            fileExtention.toUpperCase());
}

From source file:com.chiorichan.factory.event.PostImageProcessor.java

@EventHandler()
public void onEvent(PostEvalEvent event) {
    try {//w  w  w  . j av a 2  s. c  om
        if (event.context().contentType() == null
                || !event.context().contentType().toLowerCase().startsWith("image"))
            return;

        float x = -1;
        float y = -1;

        boolean cacheEnabled = AppConfig.get().getBoolean("advanced.processors.imageProcessorCache", true);
        boolean grayscale = false;

        ScriptingContext context = event.context();
        HttpRequestWrapper request = context.request();
        Map<String, String> rewrite = request.getRewriteMap();

        if (rewrite != null) {
            if (rewrite.get("serverSideOptions") != null) {
                String[] params = rewrite.get("serverSideOptions").trim().split("_");

                for (String p : params)
                    if (p.toLowerCase().startsWith("width") && x < 0)
                        x = Integer.parseInt(p.substring(5));
                    else if ((p.toLowerCase().startsWith("x") || p.toLowerCase().startsWith("w"))
                            && p.length() > 1 && x < 0)
                        x = Integer.parseInt(p.substring(1));
                    else if (p.toLowerCase().startsWith("height") && y < 0)
                        y = Integer.parseInt(p.substring(6));
                    else if ((p.toLowerCase().startsWith("y") || p.toLowerCase().startsWith("h"))
                            && p.length() > 1 && y < 0)
                        y = Integer.parseInt(p.substring(1));
                    else if (p.toLowerCase().equals("thumb")) {
                        x = 150;
                        y = 0;
                        break;
                    } else if (p.toLowerCase().equals("bw") || p.toLowerCase().equals("grayscale"))
                        grayscale = true;
            }

            if (request.getArgument("width") != null && request.getArgument("width").length() > 0)
                x = request.getArgumentInt("width");

            if (request.getArgument("height") != null && request.getArgument("height").length() > 0)
                y = request.getArgumentInt("height");

            if (request.getArgument("w") != null && request.getArgument("w").length() > 0)
                x = request.getArgumentInt("w");

            if (request.getArgument("h") != null && request.getArgument("h").length() > 0)
                y = request.getArgumentInt("h");

            if (request.getArgument("thumb") != null) {
                x = 150;
                y = 0;
            }

            if (request.hasArgument("bw") || request.hasArgument("grayscale"))
                grayscale = true;
        }

        // Tests if our Post Processor can process the current image.
        List<String> readerFormats = Arrays.asList(ImageIO.getReaderFormatNames());
        List<String> writerFormats = Arrays.asList(ImageIO.getWriterFormatNames());
        if (context.contentType() != null
                && !readerFormats.contains(context.contentType().split("/")[1].toLowerCase()))
            return;

        int inx = event.context().buffer().readerIndex();
        BufferedImage img = ImageIO.read(new ByteBufInputStream(event.context().buffer()));
        event.context().buffer().readerIndex(inx);

        if (img == null)
            return;

        float w = img.getWidth();
        float h = img.getHeight();
        float w1 = w;
        float h1 = h;

        if (x < 1 && y < 1) {
            x = w;
            y = h;
        } else if (x > 0 && y < 1) {
            w1 = x;
            h1 = x * (h / w);
        } else if (y > 0 && x < 1) {
            w1 = y * (w / h);
            h1 = y;
        } else if (x > 0 && y > 0) {
            w1 = x;
            h1 = y;
        }

        boolean resize = w1 > 0 && h1 > 0 && w1 != w && h1 != h;
        boolean argb = request.hasArgument("argb") && request.getArgument("argb").length() == 8;

        if (!resize && !argb && !grayscale)
            return;

        // Produce a unique encapsulated id based on this image processing request
        String encapId = SecureFunc.md5(context.filename() + w1 + h1 + request.getArgument("argb") + grayscale);
        File tmp = context.site() == null ? AppConfig.get().getDirectoryCache()
                : context.site().directoryTemp();
        File file = new File(tmp, encapId + "_" + new File(context.filename()).getName());

        if (cacheEnabled && file.exists()) {
            event.context().resetAndWrite(FileUtils.readFileToByteArray(file));
            return;
        }

        Image image = resize ? img.getScaledInstance(Math.round(w1), Math.round(h1),
                AppConfig.get().getBoolean("advanced.processors.useFastGraphics", true) ? Image.SCALE_FAST
                        : Image.SCALE_SMOOTH)
                : img;

        // TODO Report malformed parameters to user

        if (argb) {
            FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(),
                    new RGBColorFilter((int) Long.parseLong(request.getArgument("argb"), 16)));
            image = Toolkit.getDefaultToolkit().createImage(filteredSrc);
        }

        BufferedImage rtn = new BufferedImage(Math.round(w1), Math.round(h1), img.getType());
        Graphics2D graphics = rtn.createGraphics();
        graphics.drawImage(image, 0, 0, null);
        graphics.dispose();

        if (grayscale) {
            ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
            op.filter(rtn, rtn);
        }

        if (resize)
            Log.get().info(EnumColor.GRAY + "Resized image from " + Math.round(w) + "px by " + Math.round(h)
                    + "px to " + Math.round(w1) + "px by " + Math.round(h1) + "px");

        if (rtn != null) {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();

            if (context.contentType() != null
                    && writerFormats.contains(context.contentType().split("/")[1].toLowerCase()))
                ImageIO.write(rtn, context.contentType().split("/")[1].toLowerCase(), bs);
            else
                ImageIO.write(rtn, "png", bs);

            if (cacheEnabled && !file.exists())
                FileUtils.writeByteArrayToFile(file, bs.toByteArray());

            event.context().resetAndWrite(bs.toByteArray());
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return;
}