Example usage for java.awt.image BufferedImage getType

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

Introduction

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

Prototype

public int getType() 

Source Link

Document

Returns the image type.

Usage

From source file:com.sire.web.CajFacturaEnviadaBean.java

private void savePicture() {
    if (file != null) {
        try {//from   www .j  ava  2  s.  com
            BufferedImage originalImage = ImageIO.read(file.getInputstream());

            BufferedImage outputImage = new BufferedImage((int) (originalImage.getWidth() * 0.25),
                    (int) (originalImage.getHeight() * 0.25), originalImage.getType());

            Graphics2D g2d = outputImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, (int) (originalImage.getWidth() * 0.25),
                    (int) (originalImage.getHeight() * 0.25), null);
            g2d.dispose();

            String imagesFolder = System.getProperty("imagesFolder");

            if (imagesFolder == null) {
                String currentUsersHomeDir = System.getProperty("user.home");
                imagesFolder = currentUsersHomeDir + File.separator + "photos";
            }

            Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
            ImageWriter writer = (ImageWriter) iter.next();
            ImageWriteParam iwp = writer.getDefaultWriteParam();

            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            float quality = 1.0f; // reduce quality by 0%  
            iwp.setCompressionQuality(quality);

            File f = new File(imagesFolder + File.separator + fileName);
            try (FileImageOutputStream output = new FileImageOutputStream(f)) {
                writer.setOutput(output);

                IIOImage image = new IIOImage(outputImage, null, null);
                writer.write(null, image, iwp);
                writer.dispose();
            }
        } catch (IOException ex) {
            LOGGER.severe(ex.getMessage());
        }
    }
}

From source file:dcstore.web.ImagesWeb.java

private void resizeImage(String inPath, int w, int h, String outPath) {
    try {/*  w w w.j  a v  a 2  s.c  o m*/
        BufferedImage originalImage = ImageIO.read(new File(inPath));
        int ow, oh;
        ow = originalImage.getWidth();
        oh = originalImage.getHeight();
        double ratio = (double) ow / (double) oh;
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        int ch = (int) Math.round(w / ratio);

        BufferedImage resizedImage = new BufferedImage(w, h, type);
        Graphics2D g = resizedImage.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Color.white);
        g.fillRect(0, 0, w, h);
        g.drawImage(originalImage, 0, (int) (((float) h - (float) ch) / 2), w, ch, null);
        g.dispose();
        ImageIO.write(resizedImage, "jpg", new File(outPath));
    } catch (Exception e) {
        FacesContext.getCurrentInstance().addMessage("",
                new FacesMessage("Error while resizeing image: " + e.getMessage()));
    }
}

From source file:jp.canetrash.maven.plugin.bijint.BujintMojo.java

/**
 * ??????????//from w ww . ja  va 2  s  .co m
 * 
 * @param url
 * @return
 * @throws Exception
 */
BufferedImage getFittingImage(String url) throws Exception {
    // ??
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = buildDefaultHttpMessage(new HttpGet(url));
    httpget.setHeader("Referer", "http://www.bijint.com/jp/");
    HttpResponse response = httpclient.execute(httpget);

    BufferedImage image = ImageIO.read(response.getEntity().getContent());
    httpclient.getConnectionManager().shutdown();

    int width = image.getWidth() / 10 * 4;
    int height = image.getHeight() / 10 * 4;
    BufferedImage resizedImage = null;
    resizedImage = new BufferedImage(width, height, image.getType());
    resizedImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING), 0,
            0, width, height, null);
    return resizedImage;
}

From source file:com.github.pitzcarraldo.dissimilar.Dissimilar.java

/**
 * Compare two files, according to parameters passed via command line
 * @param pOne first file to compare//  w ww.jav  a2 s .c om
 * @param pTwo second file to compare
 * @param pHeatMapImage file to save ssim heat map image to
 * @param pCalcSSIM whether or not to calculate ssim
 * @param pCalcPSNR whether or not to calculate psnr
 */
private static void compare(final File pOne, final File pTwo, final String pHeatMapImage,
        final boolean pCalcSSIM, final boolean pCalcPSNR) {

    //just load the images once and use the internal methods for calculating ssim/psnr
    long time = System.currentTimeMillis();
    BufferedImage imageOne = null;
    try {
        imageOne = Imaging.getBufferedImage(pOne);
    } catch (IOException e) {
        printError(pOne, false, false, pTwo, false);
        return;
    } catch (NullPointerException e) {
        printError(pOne, false, false, pTwo, false);
        return;
    } catch (ImageReadException e) {
        printError(pOne, false, false, pTwo, false);
        return;
    }
    final long oneLoadTime = System.currentTimeMillis() - time;
    //getRGB only returns 8 bits per component, so what about 16-bit images?
    final int[] oneA = imageOne.getRGB(0, 0, imageOne.getWidth(), imageOne.getHeight(), null, 0,
            imageOne.getWidth());
    final int width = imageOne.getWidth();
    final int height = imageOne.getHeight();
    final boolean greyscale = (imageOne.getType() == BufferedImage.TYPE_BYTE_GRAY
            || imageOne.getType() == BufferedImage.TYPE_USHORT_GRAY);
    imageOne = null;
    time = System.currentTimeMillis();
    BufferedImage imageTwo = null;
    try {
        imageTwo = Imaging.getBufferedImage(pTwo);
    } catch (IOException e) {
        printError(pOne, true, true, pTwo, false);
        return;
    } catch (NullPointerException e) {
        printError(pOne, true, true, pTwo, false);
        return;
    } catch (ImageReadException e) {
        printError(pOne, true, true, pTwo, false);
        return;
    }
    final long twoLoadTime = System.currentTimeMillis() - time;

    //getRGB only returns 8 bits per component, so what about 16-bit images?
    final int[] twoA = imageTwo.getRGB(0, 0, imageTwo.getWidth(), imageTwo.getHeight(), null, 0,
            imageTwo.getWidth());
    imageTwo = null;

    //calculate psnr if wanted
    time = System.currentTimeMillis();
    double psnr = 0;
    long psnrCalc = 0;
    if (pCalcPSNR) {
        psnr = calcPSNR(oneA, twoA, greyscale);
        psnrCalc = System.currentTimeMillis() - time;
    }

    //calculate ssim if wanted
    time = System.currentTimeMillis();
    List<Double> ssimMin = new LinkedList<Double>();
    List<Double> ssimVariance = new LinkedList<Double>();
    double ssim = 0;
    long ssimCalc = 0;
    if (pCalcSSIM) {
        ssim = calcSSIM(oneA, twoA, width, height, greyscale, pHeatMapImage, ssimMin, ssimVariance);
        ssimCalc = System.currentTimeMillis() - time;
    }

    System.out.println("<dissimilar version=\"" + version + "\">");
    System.out.println("     <file loadTimeMS=\"" + oneLoadTime + "\">" + pOne + "</file>");
    System.out.println("     <file loadTimeMS=\"" + twoLoadTime + "\">" + pTwo + "</file>");
    if (pCalcSSIM) {
        System.out.println("     <ssim calcTimeMS=\"" + ssimCalc + "\">");
        if (ssim > 0) {
            System.out.println("          <mean>" + new DecimalFormat("0.0000000").format(ssim) + "</mean>");
            System.out.println(
                    "          <min>" + new DecimalFormat("0.0000000").format(ssimMin.get(0)) + "</min>");
            System.out.println("          <variance>"
                    + new DecimalFormat("0.0000000").format(ssimVariance.get(0)) + "</variance>");
        } else {
            System.out.println("failed");
        }
        System.out.println("     </ssim>");
    }
    if (pCalcPSNR) {
        System.out.println("     <psnr calcTimeMS=\"" + psnrCalc + "\">"
                + new DecimalFormat("0.0000").format(psnr) + "</psnr>");
    }
    System.out.println("</dissimilar>");

}

From source file:com.funambol.foundation.util.MediaUtils.java

/**
 * Rotates given buffered image by given amount of degree.
 * The valid degree values are 0, 90, 180, 270.
 * If the image is a jpg, the rotation is lossless, exif data are preserved
 * and image size is almost the same.//  www  .  ja  v a2 s  .  co m
 *
 * @param bufImage the buffered image
 * @param degree amount of degree to apply
 * @return a buffered image containing rotated image data
 * @throws PicturesException if amount of degree is invalid or if an
 *         IOException occurs
 */
private static BufferedImage rotateImage(BufferedImage bufImage, int degree)
        throws FileDataObjecyUtilsException {

    degree = degree % 360;
    int h;
    int w;

    switch (degree) {
    case 0:
    case 180:
        h = bufImage.getHeight();
        w = bufImage.getWidth();
        break;
    case 90:
    case 270:
        h = bufImage.getWidth();
        w = bufImage.getHeight();
        break;
    default:
        throw new FileDataObjecyUtilsException(
                "Error rotating image since the '" + degree + "' degree value is unsupported");
    }

    BufferedImage out = null;

    int bufImageType = bufImage.getType();
    if (BufferedImage.TYPE_BYTE_INDEXED == bufImageType || BufferedImage.TYPE_BYTE_BINARY == bufImageType) {

        IndexColorModel model = (IndexColorModel) bufImage.getColorModel();
        out = new BufferedImage(w, h, bufImage.getType(), model);

    } else if (BufferedImage.TYPE_CUSTOM == bufImageType) {

        // we don't know what type of image it can be

        // there's a bug in some VM that cause some PNG images to have 
        // type custom: this should take care of this issue

        //check if we need to have alpha channel
        boolean alpha = bufImage.getTransparency() != BufferedImage.OPAQUE;

        if (alpha) {
            // TYPE_INT_ARGB_PRE gives you smaller output images
            // than TYPE_INT_ARGB
            out = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
        } else {
            out = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        }

    } else {

        out = new BufferedImage(w, h, bufImage.getType());
    }

    Graphics2D g2d = out.createGraphics();

    Map renderingHints = new HashMap();

    renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

    g2d.setRenderingHints(renderingHints);
    g2d.rotate(Math.toRadians(degree));

    switch (degree) {
    case 90:
        g2d.translate(0, -w);
        break;
    case 180:
        g2d.translate(-w, -h);
        break;
    case 270:
        g2d.translate(-h, 0);
        break;
    }

    g2d.drawImage(bufImage, null, 0, 0);
    g2d.dispose();

    return out;
}

From source file:Main.java

/**
 * Paints a set of {@link Rectangle} object out of a rendered {@link BufferedImage}
 * such that the resulting image is transparent except for a minimum bounding
 * rectangle of the selected elements./*from  w ww  .j a  va 2  s  . c o m*/
 *
 * @param image the source image
 * @param rectangles the set of rectangles to copy
 * @param boundingBox the bounding rectangle of the set of rectangles to copy, can be
 *            computed by {@link ImageUtils#getBoundingRectangle}
 * @param scale a scale factor to apply to the result, e.g. 0.5 to shrink the
 *            destination down 50%, 1.0 to leave it alone and 2.0 to zoom in by
 *            doubling the image size
 * @return a rendered image, or null
 */
public static BufferedImage drawRectangles(BufferedImage image, java.util.List<Rectangle> rectangles,
        Rectangle boundingBox, double scale) {

    // This code is not a test. When I implemented image cropping, I first implemented
    // it for BufferedImages (since it's easier; easy image painting, easy scaling,
    // easy transparency handling, etc). However, this meant that we would need to
    // convert the SWT images from the ImageOverlay to BufferedImages, crop and convert
    // back; not ideal, so I rewrote it in SWT (see SwtUtils). However, I
    // don't want to throw away the code in case we start keeping BufferedImages rather
    // than SWT images or need it for other purposes, but rather than place it in the
    // production codebase I'm leaving this utility here in the associated ImageUtils
    // test class. It was used like this:
    // @formatter:off
    //
    //    BufferedImage wholeImage = SwtUtils.convertToAwt(image);
    //    BufferedImage result = ImageUtils.cropSelection(wholeImage,
    //        rectangles, boundingBox, scale);
    //    e.image = SwtUtils.convertToSwt(image.getDevice(), result, true,
    //        DRAG_TRANSPARENCY);
    //
    // @formatter:on

    if (boundingBox == null) {
        return null;
    }

    int destWidth = (int) (scale * boundingBox.width);
    int destHeight = (int) (scale * boundingBox.height);
    BufferedImage dest = new BufferedImage(destWidth, destHeight, image.getType());

    Graphics2D g = dest.createGraphics();

    for (Rectangle bounds : rectangles) {
        int dx1 = bounds.x - boundingBox.x;
        int dy1 = bounds.y - boundingBox.y;
        int dx2 = dx1 + bounds.width;
        int dy2 = dy1 + bounds.height;

        dx1 *= scale;
        dy1 *= scale;
        dx2 *= scale;
        dy2 *= scale;

        int sx1 = bounds.x;
        int sy1 = bounds.y;
        int sx2 = sx1 + bounds.width;
        int sy2 = sy1 + bounds.height;

        g.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
    }

    g.dispose();

    return dest;
}

From source file:com.cmart.PageControllers.SellItemImagesController.java

public void saveImages(String baseURL) {
    //System.out.println("sellitemimagecont: looking for image to upload!");
    //System.out.println("saving images :" + baseURL);
    baseURL = baseURL + "/" + GV.REMOTE_IMAGE_DIR + "/";

    // Special case for the thumbnail
    /*if(this.images.size()>1){
       FileItem image = this.images.get(0);
               /*from ww  w.j  av  a 2s.c  o m*/
       //TODO: compress an image
       String[] ext = image.getName().split("\\.");
       int extIndex = ext.length>0 ? ext.length-1 : 0;
       String filename = this.itemID + "_" + 0 + "." + ext[extIndex];
       String URL = filename;
               
       // Setup the thumbnail file
       File file = new File(GlobalVars.localImageDir, filename);
       file.setReadable(true, false);
       file.setWritable(true, false);
               
       try {
    image.write(file);
            
    GlobalVars.db.insertThumbnail(this.itemID, URL);
       } catch (Exception e) {
    // TODO Auto-generated catch block
    this.errors.add(new Error("SellItemImagesController (saveImages): Could not save thumbnail", e));
    e.printStackTrace();
       }
    }*/
    boolean thumbnail = true;

    // Loop through all the images
    for (int i = 0; i < this.images.size(); i++) {
        FileItem image = this.images.get(i);

        //TODO: make number start from one and only count real images

        if (image.getSize() > 0) {
            // Make the file name and path
            String[] ext = image.getName().split("\\.");
            int extIndex = ext.length > 0 ? ext.length - 1 : 0;
            String filename = this.itemID + "_" + (i + 1) + "." + ext[extIndex];
            //String URL = filename;

            // Setup the image file
            //System.out.println("setting temp dir as the image");
            File file = new File(GV.LOCAL_TEMP_DIR, filename + "tmp");
            file.setReadable(true, false);
            file.setWritable(true, false);

            //System.out.println("URL :" + URL);
            //System.out.println("name :" + filename);
            //System.out.println("local :" + GV.LOCAL_IMAGE_DIR);
            //System.out.println("remote :" + GV.REMOTE_IMAGE_DIR);

            try {
                //System.out.println("doing db insert");
                GV.DB.insertImage(this.itemID, i + 1, filename, "");

                //System.out.println("saving image");
                image.write(file);

                //System.out.println("mkaing file in img dir");
                File file2 = new File(GV.LOCAL_IMAGE_DIR, filename);

                //System.out.println("doing the image resize");
                BufferedImage originalImage2 = ImageIO.read(file);
                int type2 = originalImage2.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                        : originalImage2.getType();

                //System.out.println("doing the image resize second step");
                BufferedImage resizeImageHintJpg2 = resizeImageWithHint(originalImage2, type2, 500, 450);
                ImageIO.write(resizeImageHintJpg2, "jpg", file2);

                try {
                    file.delete();
                } catch (Exception e) {

                }

                //System.out.println("sellitemimagecont: inserted an image!");

                if (thumbnail) {
                    //TODO: some image compression
                    String thumbName = this.itemID + "_" + 0 + "." + ext[extIndex];
                    GV.DB.insertThumbnail(this.itemID, thumbName);

                    //System.out.println("doing thumbnail");

                    File thumbFile = new File(GV.LOCAL_IMAGE_DIR, thumbName);

                    // Get a JPEG writer
                    // TODO: other formats??
                    /*ImageWriter writer = null;
                      Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
                      if (iter.hasNext()) {
                          writer = (ImageWriter)iter.next();
                      }
                            
                      // Set the output file
                      ImageOutputStream ios = ImageIO.createImageOutputStream(thumbFile);
                      writer.setOutput(ios);
                              
                      // Set the compression level
                      JPEGImageWriteParam imgparams = new JPEGImageWriteParam(Locale.getDefault());
                      imgparams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
                      imgparams.setCompressionQuality(128);
                              
                      // Write the compressed file
                      RenderedImage rendFile = ImageIO.read(file);
                      writer.write(null, new IIOImage(rendFile, null, null), imgparams);
                              
                              
                              
                            
                    // copy file
                    InputStream fin = new FileInputStream(file);
                    OutputStream fout = new FileOutputStream(thumbFile);
                    byte[] buff = new byte[1024];
                    int len;
                            
                    while((len = fin.read(buff)) > 0)
                         fout.write(buff, 0, len);
                            
                    fin.close();
                    fout.close();
                    */

                    BufferedImage originalImage = ImageIO.read(file2);
                    int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                            : originalImage.getType();

                    BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type, 100, 100);
                    ImageIO.write(resizeImageHintJpg, "jpg", thumbFile);

                    thumbnail = false;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                this.errors.add(new Error("SellItemImagesController (saveImages): Could not save image", e));
                e.printStackTrace();
            }
        }
    }

    if (this.errors.size() == 0 && !this.useHTML5()) {
        createRedirectURL();
    }

    // Try to save the uploaded files
    /*try {
               
       while(images.hasNext()) {
    FileItem item = (FileItem) images.next();
    System.out.println("doing item 1");
    /*
     * Handle Form Fields.
     *
    if(item.isFormField()) {
       System.out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
    } else {
       //Handle Uploaded files.
       System.out.println("Field Name = "+item.getFieldName()+
          ", File Name = "+item.getName()+
          ", Content type = "+item.getContentType()+
          ", File Size = "+item.getSize());
       /*
        * Write file to the ultimate location.
        *
       File file = new File(GlobalVars.imageDir,item.getName());
       item.write(file);
    }
    //System.out.close();
       }
    }catch(Exception ex) {
       System.out.println("Error encountered while uploading file");
    }*/
}

From source file:org.geowebcache.service.wms.WMSTileFuser.java

protected void scaleRaster() {
    if (canvasSize[0] != reqWidth || canvasSize[1] != reqHeight) {
        BufferedImage preTransform = canvas;

        canvas = new BufferedImage(reqWidth, reqHeight, preTransform.getType());

        Graphics2D gfx = canvas.createGraphics();

        AffineTransform affineTrans = AffineTransform.getScaleInstance(
                ((double) reqWidth) / preTransform.getWidth(), ((double) reqHeight) / preTransform.getHeight());

        log.debug("AffineTransform: " + (((double) reqWidth) / preTransform.getWidth()) + ","
                + +(((double) reqHeight) / preTransform.getHeight()));
        // Hints settings
        RenderingHints hintsTemp = HintsLevel.DEFAULT.getRenderingHints();

        if (hints != null) {
            hintsTemp = hints;/* w  w  w.j a  v  a  2s .  c o m*/
        }
        gfx.addRenderingHints(hintsTemp);
        gfx.drawRenderedImage(preTransform, affineTrans);
        gfx.dispose();
    }
}

From source file:net.pkhsolutions.pecsapp.control.PictureTransformer.java

/**
 * TODO Document me//from ww  w.j  a  v a 2 s.  co  m
 *
 * @param image
 * @param maxHeightInPx
 * @param maxWidthInPx
 * @return
 */
@NotNull
public BufferedImage scaleIfNecessary(@NotNull BufferedImage image, int maxHeightInPx, int maxWidthInPx) {
    int w = image.getWidth();
    int h = image.getHeight();

    int newW;
    int newH;

    if (w <= maxWidthInPx && h <= maxHeightInPx) {
        return image;
    } else if (w > h) {
        newW = maxWidthInPx;
        newH = newW * h / w;
    } else {
        newH = maxHeightInPx;
        newW = newH * w / h;
    }
    LOGGER.info("Original size was w{} x h{}, new size is w{} x h{}", w, h, newW, newH);
    Image tmp = image.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage img = new BufferedImage(newW, newH, image.getType());
    Graphics2D g2d = img.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();
    return img;
}

From source file:algorithm.ImageImageFrameExpanding.java

private BufferedImage getOutputImage(BufferedImage carrierImage, BufferedImage payloadImage) {
    int outputWidth = Math.max(carrierImage.getWidth(), payloadImage.getWidth());
    int outputHeight = carrierImage.getHeight() + payloadImage.getHeight() + METADATA_HEIGHT;
    return new BufferedImage(outputWidth, outputHeight, carrierImage.getType());
}