Example usage for java.awt.image BufferedImage getScaledInstance

List of usage examples for java.awt.image BufferedImage getScaledInstance

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getScaledInstance.

Prototype

public Image getScaledInstance(int width, int height, int hints) 

Source Link

Document

Creates a scaled version of this image.

Usage

From source file:org.ofbiz.product.imagemanagement.ImageManagementServices.java

public static Map<String, Object> resizeImageThumbnail(BufferedImage bufImg, double imgHeight,
        double imgWidth) {

    /* VARIABLES */
    BufferedImage bufNewImg;//from  w w  w  .j  a  v a 2 s.  c  o  m
    double defaultHeight, defaultWidth, scaleFactor;
    Map<String, Object> result = FastMap.newInstance();

    /* DIMENSIONS from ImageProperties */
    defaultHeight = 100;
    defaultWidth = 100;

    /* SCALE FACTOR */
    // find the right Scale Factor related to the Image Dimensions
    if (imgHeight > imgWidth) {
        scaleFactor = defaultHeight / imgHeight;

        // get scaleFactor from the smallest width
        if (defaultWidth < (imgWidth * scaleFactor)) {
            scaleFactor = defaultWidth / imgWidth;
        }
    } else {
        scaleFactor = defaultWidth / imgWidth;
        // get scaleFactor from the smallest height
        if (defaultHeight < (imgHeight * scaleFactor)) {
            scaleFactor = defaultHeight / imgHeight;
        }
    }

    int bufImgType;
    if (BufferedImage.TYPE_CUSTOM == bufImg.getType()) {
        // apply a type for image majority
        bufImgType = BufferedImage.TYPE_INT_ARGB_PRE;
    } else {
        bufImgType = bufImg.getType();
    }

    // scale original image with new size
    Image newImg = bufImg.getScaledInstance((int) (imgWidth * scaleFactor), (int) (imgHeight * scaleFactor),
            Image.SCALE_SMOOTH);

    bufNewImg = ImageTransform.toBufferedImage(newImg, bufImgType);

    result.put("bufferedImage", bufNewImg);
    result.put("scaleFactor", scaleFactor);
    return result;
}

From source file:de.fhg.fokus.openride.services.profile.ProfileService.java

@POST
@Path("picture/")
@Produces("text/json")
public Response postPicture(@Context HttpServletRequest con, @PathParam("username") String username) {

    System.out.println("postPicture start");

    boolean success = false;

    //String profilePicturesPath = "C:\\OpenRide\\pictures\\profile";
    String profilePicturesPath = "../OpenRideWeb/img/profile/default";

    //TODO/*ww w  .ja  v  a 2 s  . com*/
    //String imagePath = getServletConfig().getInitParameter("imagePath");

    // FIXME: The following try/catch may be removed for production deployments:
    /*try {
    if (java.net.InetAddress.getLocalHost().getHostName().equals("elan-tku-r2032.fokus.fraunhofer.de")) {
        profilePicturesPath = "/mnt/windows/OpenRide/pictures/profile";
    }
    else if (java.net.InetAddress.getLocalHost().getHostName().equals("robusta2.fokus.fraunhofer.de")) {
        profilePicturesPath = "/usr/lib/openride/pictures/profile";
    }
    } catch (UnknownHostException ex) {
    }*/

    int picSize = 125;
    int picThumbSize = 60;

    // check if remote user == {username} in path param
    if (!username.equals(con.getRemoteUser())) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }

    if (ServletFileUpload.isMultipartContent(con)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(con);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (items != null) {
            Iterator<FileItem> iter = items.iterator();

            CustomerEntity c = customerControllerBean.getCustomerByNickname(username);
            String uploadedFileName = c.getCustNickname() + "_" + c.getCustId();

            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField() && item.getSize() > 0) {

                    try {
                        BufferedImage uploadedPicture = ImageIO.read(item.getInputStream());

                        int newWidth, newHeight;
                        int xPos, yPos;
                        float ratio = (float) uploadedPicture.getHeight() / (float) uploadedPicture.getWidth();

                        // Resize for "large" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        Image resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picSize - newWidth) / 2);
                        yPos = Math.round((picSize - newHeight) / 2);
                        BufferedImage bim = new BufferedImage(picSize, picSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picSize, picSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        File outputPicture = new File(profilePicturesPath, uploadedFileName + ".jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                        // Resize again for "thumb" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picThumbSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picThumbSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picThumbSize - newWidth) / 2);
                        yPos = Math.round((picThumbSize - newHeight) / 2);
                        bim = new BufferedImage(picThumbSize, picThumbSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picThumbSize, picThumbSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        outputPicture = new File(profilePicturesPath, uploadedFileName + "_thumb.jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("File upload / resize unsuccessful.");
                    }
                    success = true;
                }
            }
        }
    }

    if (success) {

        // TODO: Perhaps introduce a redirection target as a parameter to the putProfile method and redirect to that URL (code 301/302) instead of just doing nothing.
        return null;

        /*
        try {
        String referer = con.getHeader("HTTP_REFERER");
        System.out.println("putPicture: Referer: " + referer);
        if (referer != null)
        return Response.status(Response.Status.SEE_OTHER).contentLocation(new URI(referer)).build();
        else
        return Response.ok().build();
        } catch (URISyntaxException ex) {
        Logger.getLogger(ProfileService.class.getName()).log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.BAD_REQUEST).build();
        }
         */
    } else {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}

From source file:org.ofbiz.product.imagemanagement.ImageManagementServices.java

public static Map<String, Object> resizeImage(BufferedImage bufImg, double imgHeight, double imgWidth,
        double resizeHeight, double resizeWidth) {

    /* VARIABLES */
    BufferedImage bufNewImg;/*from   w ww  . ja  v  a 2 s.  c  o  m*/
    double defaultHeight, defaultWidth, scaleFactor;
    Map<String, Object> result = FastMap.newInstance();

    /* DIMENSIONS from ImageProperties */
    defaultHeight = resizeHeight;
    defaultWidth = resizeWidth;

    /* SCALE FACTOR */
    // find the right Scale Factor related to the Image Dimensions
    if (imgHeight > imgWidth) {
        scaleFactor = defaultHeight / imgHeight;

        // get scaleFactor from the smallest width
        if (defaultWidth < (imgWidth * scaleFactor)) {
            scaleFactor = defaultWidth / imgWidth;
        }
    } else {
        scaleFactor = defaultWidth / imgWidth;
        // get scaleFactor from the smallest height
        if (defaultHeight < (imgHeight * scaleFactor)) {
            scaleFactor = defaultHeight / imgHeight;
        }
    }

    int bufImgType;
    if (BufferedImage.TYPE_CUSTOM == bufImg.getType()) {
        // apply a type for image majority
        bufImgType = BufferedImage.TYPE_INT_ARGB_PRE;
    } else {
        bufImgType = bufImg.getType();
    }

    // scale original image with new size
    Image newImg = bufImg.getScaledInstance((int) (imgWidth * scaleFactor), (int) (imgHeight * scaleFactor),
            Image.SCALE_SMOOTH);

    bufNewImg = ImageTransform.toBufferedImage(newImg, bufImgType);

    result.put("bufferedImage", bufNewImg);
    result.put("scaleFactor", scaleFactor);
    return result;
}

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  ww  .j av a  2s.co  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:at.tuwien.ifs.somtoolbox.apps.viewer.MapPNode.java

public void setBackgroundImage(BufferedImage background) {
    if (backgroundImage != null) { // remove a possibly already existing background iamge
        removeChild(backgroundImage);//ww  w .ja  v  a 2  s .  c  o  m
    }
    originalBackgroundImage = background;
    backgroundImage = new PImage(background.getScaledInstance(getBackgroundImageWidth(),
            getBackgroundImageHeight(), Image.SCALE_SMOOTH));
    backgroundImage.setPickable(false);
    setBackgroundImageVisibility(true);
}

From source file:sms.Form1Exams.java

public void showimg() throws Exception {
    this.icon.setIcon(null);
    this.icon.setText(" no image");
    try {//w  w w .  j a  v a  2  s  .  c  o  m
        methods m = new methods();
        // Connection con = m.getConnection();
        Connection con = m.getConnection();
        Statement st2 = con.createStatement();

        ResultSet res7 = st2.executeQuery("SELECT imgurl FROM students  WHERE id='" + this.sid.getText() + "'");
        if (res7.next()) {
            this.filePath = res7.getString("imgurl");

            st2.close();
            res7.close();
            con.close();
            String op = "image";
            if (this.filePath.equals(op)) {
                this.icon.setIcon(null);
                this.icon.setIcon(null);
                this.icon.setText(" no image");
            } else {
                BufferedImage img = null;
                try {
                    img = ImageIO.read(new java.io.File(this.filePath));
                    this.fileurlp = this.filePath.replace("\\", "\\\\");
                } catch (IOException e) {
                    // JOptionPane.showMessageDialog(null, "error loading image \n  make sure image is in images folder ");

                    this.icon.setIcon(null);
                    this.icon.setText(" no image");
                }
                Image dimg = img.getScaledInstance(this.icon.getWidth(), this.icon.getHeight(), 4);

                ImageIcon icon = new ImageIcon(dimg);
                this.icon.setText("");
                this.icon.setIcon(icon);
            }
        } else {
            this.icon.setText(" no image");
            //JOptionPane.showMessageDialog(null, "error loading image \n  make sure image is in images folder ");
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

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

@EventHandler()
public void onEvent(PostEvalEvent event) {
    try {/*from   www  .ja  va 2s. c o m*/
        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;
}

From source file:com.SE.myPlayer.MusicPlayerGUI.java

private void clipArtSet(String SongLocation) throws IOException, InvalidDataException, UnsupportedTagException {
        song = new Mp3File(SongLocation);
        songLengthSeconds = song.getLengthInSeconds();
        totaltimeLabel.setText(getTime(songLengthSeconds));
        pointerDegress = (int) songLengthSeconds;
        if (song.hasId3v2Tag()) {
            ID3v2 id3v2tag = song.getId3v2Tag();
            byte[] imageData = id3v2tag.getAlbumImage();
            if (imageData != null) {
                BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData));
                ImageIcon icon = new ImageIcon(img.getScaledInstance(102, 102, 12));
                clipArt.setIcon(icon);//from www .  ja  v a  2 s .co  m
            } else {
                setDefaultClipArt();
            }
        }
    }

From source file:org.jopac2.jbal.iso2709.Unimarc.java

@Override
public void setImage(BufferedImage image, int maxx, int maxy) {
    if (image == null) {
        try {//  w  ww  .  j  a  va2 s.c o m
            removeTags("911");
        } catch (JOpac2Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return;
    }
    ByteArrayOutputStream a = new ByteArrayOutputStream();
    try {
        Image im = image.getScaledInstance(maxx, maxy, Image.SCALE_SMOOTH);
        BufferedImage dest = new BufferedImage(maxx, maxy, BufferedImage.TYPE_INT_RGB);
        dest.createGraphics().drawImage(im, 0, 0, null);
        ImageIO.write(dest, "jpeg", a);
        String coded = Base64.encode(a.toByteArray());
        Tag t = new Tag("911", ' ', ' ');
        t.addField(new Field("a", coded));
        try {
            removeTags("911");
        } catch (JOpac2Exception e) {
        }
        addTag(t);
        a.reset();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:paquete.HollywoodUI.java

public BufferedImage resize(BufferedImage img, int newW, int newH) {
    Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);//  ww w  .j a v  a  2 s.co  m
    g2d.dispose();

    return dimg;
}