EzDevInfo.com

imgscalr

Simple Java image-scaling library implementing Chris Campbell's incremental scaling algorithm as well as Java2D's "best-practices" image-scaling techniques. imgscalr – Java Image Scaling Library | The Buzz Media sections description license what problem does this solve? benefits usage intended audience download javadoc & source maven imgscalr

How to resize images in a directory?

This code attempts to resize images in a directory called "imgs". Unfortunately for some reason when I uncomment the listFiles(..) loop ImageIO.read(sourceImageFile) will return null. Yet processing the same file straightaway outside the loop (res("imgs/foto_3.jpg")) works. So apparently, this loop is preventing the files from being read. Solutions?

import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import static org.imgscalr.Scalr.*;

public class App {

    public static void main(String[] args) throws IOException {
//        for (File sourceImageFile : new File("imgs").listFiles()) {
//            res("imgs/"+sourceImageFile.getName());
//        }
        res("imgs/foto_3.jpg");

    }

    public static void res(String arg) throws IOException {

        File sourceImageFile = new File(arg);
        BufferedImage img = ImageIO.read(sourceImageFile);

        BufferedImage thumbnail = resize(img, 500);

        thumbnail.createGraphics().drawImage(thumbnail, 0, 0, null);
        ImageIO.write(thumbnail, "jpg", new File("resized/" + sourceImageFile.getName()));
    }
}

enter image description here

To reproduce the problem you can download the Maven project.


Source: (StackOverflow)

Android How to use Scalr 4.2 or 'java-image-scaling' for HQ thumbnails

I'm trying to create high quality thumbnails, have tried most-if-not-all methods with Android and not yet satisfied.

Here is a good post I found, in which I would like to try using Scalr or 'java-image-scaling' library for Android.

Here are Scalr and 'java-image-scaling'

Question: Can I use them in Android dev and How? (since I didn't see it mentions anywhere)


Source: (StackOverflow)

Advertisements

Scale large images using Java and AsyncScalr

I'm using AsyncScalr in a Servlet to scale down some large images (~ 10-15 MegaBytes), the actual resizing process takes about 40ms which is not much. The overkill comes from Reading the Image from Local Storage as a BufferedImage. so the times are mostly like :

read the image file : 1630ms !! resizing the image : 41ms writing the image : 40ms

below is the code that I'm using, is there any more optimal way to do this?

        final FileImageInputStream fileImageInputStream = new FileImageInputStream(file);
        BufferedImage bufferedImage = ImageIO.read(fileImageInputStream);

        // resize file
        Future<BufferedImage> result = AsyncScalr.resize(bufferedImage, Method.SPEED, width, OP_ANTIALIAS, OP_BRIGHTER);
        try {
            bufferedImage = result.get();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        catch (ExecutionException e) {
            e.printStackTrace();
        }

        // Write the image
        ImageIO.write(bufferedImage, imageOutput, outputStream);

Source: (StackOverflow)

Scalr resize and crop to size

I would like to show an image in all sort of placements with different width and height.

I am using a method for crop and resize with Sclar, But I have 2 problems:

  1. The result doesn't look so good in some cases. I think it is because the image in the code is first scaled.
  2. I get an exception in other cases. For example:

Invalid crop bounds: x [32], y [-1], width [64] and height [64] must all be >= 0

What is the best way of resizing a cropping and image to some target width and height?

Here is my current method:

  public static BufferedImage resizeAndCropToCenter(BufferedImage image, int width, int height) {
    image = Scalr.resize(image, Scalr.Method.QUALITY, Scalr.Mode.FIT_TO_WIDTH,
        width * 2, height * 2, Scalr.OP_ANTIALIAS);

    int x, y;

    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();

    if (imageWidth > imageHeight) {
      x = width / 2;
      y = (imageHeight - height) / 2;
    } else {
      x = (imageWidth - width) / 2;
      y = height / 2;
    }


    return Scalr.crop(image, x, y, width, height);
  }

Source: (StackOverflow)

Compress image, using imageScalr

I am using imagescalr for resizing images, but i also want to compress the images so that the size stays below 32kb(as ie 8 supports base64 strings upto 32kb). I am resizing the image like this

Map resizeImage(BufferedImage imageData, int width, int height, String imageFormat){

    BufferedImage thumbnail =  Scalr.resize(imageData, Scalr.Method.SPEED, Scalr.Mode.FIT_EXACT ,
    width, height, Scalr.OP_ANTIALIAS);

    ByteArrayOutputStream baos = new ByteArrayOutputStream()
    ImageIO.write(thumbnail, imageFormat, baos)
    baos.flush()
    byte[] imageBytes = baos.toByteArray()
    baos.close()

    return [imageBytes:imageBytes, imageFormat:imageFormat]
}

I want a way so that i can compress with least change to the code.


Source: (StackOverflow)

Re-sizing image within java corrupts/modifies the attached clipping path, alternatives?

I've written a program that takes in a large source file(.jpeg), creates, scales down two files and dumps the source, and two other images(still .jpeg) within a given directory.

The user then edits the largest of the three images and then utilizes the program to update the two smaller images. (scale down)

The problem is, when the user edits the largest of the images they apply a clipping path, upon resizing through the java program and org.imgscalr.Scalr library the clipping path is corrupted and/or modified.

People that are more knowledgeable than I, is there any way to scale down the image and clipping path at the same time? i.e. is there any better library to utilize than org.imgscalr.Scalr?

p.s. the images need to be kept as .jpeg

Thanks in advance! :)


Source: (StackOverflow)

Image Resolution Changing but I am only trying to rotate the image

Any reason this code would changing the resolution of the original JPEG? I can understand if the file size were different because the JPEG quality settings are probably different but I don't understand why this would be resizing an image.

File newfile=new File(mydestinationfolder.concat(imagename));
Files.move(file.toPath(),newfile.toPath(), REPLACE_EXISTING);
Rotation Orientation;
if ((Orientation=Exif_data.get_Exif_Orientation(newfile)) != null) {

    System.out.println(Orientation.toString());
    BufferedImage oldimage = ImageIO.read(newfile);
    BufferedImage tmp = Scalr.rotate(oldimage, Orientation);
    oldimage.flush();
    oldimage=tmp;
    ImageIO.write(oldimage, "JPEG", newfile);

}

Source: (StackOverflow)

Imgscalar library ccompletly removes clipping path upon resize

I'm utilizing the Imgscalar library. When it scales down images, it completely removes the attached clipping path on the jpeg.

Can anyone recommend a library that handles clipping paths?


Source: (StackOverflow)

Scale Image, then save to DB (Blob)

I have just started using the imgScalr Image Scaling library.

I can get the code to scale the images (I'm pretty sure this works).

BufferedImage fullImage = Scalr.resize((BufferedImage) ImageIO.read(imageStream), fullImageSize);
BufferedImage thumbImage = Scalr.resize(fullImage, thumbImageSize);


Backstory
This is used in a tomcat6 webapp. I pass the image onto a servlet, and read it into an InputStream called "imageStream".

Before resizing/scaling the image, what I was doing was taking that InputStream and saving it to the DB (Oracle11+) Blob field using a PreparedStatement, like so:

PreparedStatement st = con.prepareStatement(SQL);
st.setBlob(1, imageStream);

This was working fine as I could save it no problem and retrieve it with no problems.


The Issue
The issue is now that I'm scaling the image(s) they are being converted to a BufferedImage which I can't save directly to the DB using my PreparedStatement.

Instead, what I'm trying to do is convert the BufferedImage to a ByteArrayOutputStream which then gets read into an InputStream, see code below:

BufferedImage fullImage = Scalr.resize((BufferedImage) ImageIO.read(imageStream), fullImageSize);
BufferedImage thumbImage = Scalr.resize(fullImage, thumbImageSize);

ByteArrayOutputStream fullImageArray = new ByteArrayOutputStream();
ByteArrayOutputStream thumbImageArray = new ByteArrayOutputStream();

ImageIO.write(fullImage, imageMimeType, fullImageArray);
ImageIO.write(thumbImage, imageMimeType, thumbImageArray);

InputStream fullImageStream = new ByteArrayInputStream(fullImageArray.toByteArray());
InputStream thumbImageStream = new ByteArrayInputStream(thumbImageArray.toByteArray());

// DB INITIALISATION STUFF

PreparedStatement st = con.prepareStatement(SQL);
st.setBlob(1, fullImageStream);
st.setBlob(2, thumbImageStream);


Error Details
When I execute the statement, I get a java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into. Which I know that it clearly means that I'm trying to insert a NULL value into the column, so that's not the issue.

The problem is that at some point during my conversions or scaling, the image value gets lost and I end up with a null


The Question
The question comes in two parts:

  1. What am I doing wrong?
  2. Is there are better way to scale an Image in java and save it to a DB (Blob) field?

Source: (StackOverflow)

ImageIO.read/write slow in Websphere 8.5.5

As a part of my web application, I am using javax.imageio.ImageIO for reading/writing BufferedImage. Initially my app was running on Tomcat 7, and it was running quite fast. Since I've deployed my app to WebSphere 8.5.5 the performance of reading/writing has significantly decreased (few times slower).

At first, I thought was that ImageIO performed bad on WebSphere due to IBM's JVM, so I've configured Tomcat to use IBM Java, and again it performed much better then on WebSphere. With Tomcat it takes around 2.5secs and with WebSphere 12secs to read, process, and write the image (size ~= 200KB).

Is there some IBM JVM specific configuration I can use in order to speed up reading of images?

Here is the extract from the code I use:

// srcImagePath & dstImagePath are both pointing 
// to the location outside app servers

BufferedImage image = ImageIO.read(new File(srcImagePath));

// here I am only resizing image using com.twelvemonkeys.image.ResampleOp
// from twelvemonkeys library
BufferedImage destImage = resizeImage(image);

ImageIO.write(destImage, "jpg", dstImagePath);

Here is the JVM configuration I have used (changed):

Tomcat 7.0.50: -Xms512m -Xmx1024m -XX:PermSize=128m -XX:MaxPermSize=512m

WebSphere 8.5.5: Initial heap size 512m, Maximum heap size: 1280m

IBM Java 1.7_64

Windows 7

Is there any WebSphere configuration I am not aware of, that could speed up the processing?


Source: (StackOverflow)

Image quality issues using Java library imgsclr to RESIZE

I have a problem with quality when I try only to RESIZE an image to a specific width and height using imgsclr 4.2(http://www.thebuzzmedia.com/imgscalr-3-2-released/comment-page-1/#comment-650387).

I have an image which 240X320 and I have to resize it to 50X75 and 120X180 . I tried both separately using the following code(I am using imgscalr 4.2).

image=resize(image,Method.ULTRA_QUALITY, 50,75, OP_ANTIALIAS, OP_BRIGHTER);
saveImage(image, ImageFormatTypes.JPEG, DESTINATION + RESIZED_IMAGE + “.”+ImageFormatTypes.JPEG);

I have two problems. #1 is very low quality compared to other internal tools I used to resize the image manually. #2. The width increases on the output from 50 to 56 and from 120 to 135 which is weird.

Do you have any idea why these are happening? I appreciate your help. Original Image Resized Image


Source: (StackOverflow)

Image is in landscape instead of portrait mode after scaling

I have an image and want to scale it down using imgscalr [1].
The source image's size is 1836 x 3264 (so it's portrait mode) and destination resolution is 1336 x 768.
The failure is that the image is in landscape mode and not portrait mode anymore after scaling. The scaling itself works like a charm.
My code:

BufferedImage src = ImageIO.read(new File("sourceimage.jpg"));
BufferedImage scaled = Scalr.resize(src, Scalr.Method.SPEED, Scalr.Mode.FIT_TO_HEIGHT, 1336, 768, Scalr.OP_ANTIALIAS);
ImageIO.write(scaled, "jpg", f);

The metadata of the file looks correct (orientation = 1).
My expactation is when downscaling an portrait picture that it is still a portrait picture after the scaling process.

I also tried some other libraries/classes like this: https://frickelblog.wordpress.com/2009/06/08/fast-image-scaling-in-java/ but the effect is the same.

Can you please help me? This one drives me crazy! I'm pretty sure there is just a detail to change.

[1] http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/#maven

edit:
Here's the original image: http://i.stack.imgur.com/NEc8j.jpg
the scaled version: http://i.stack.imgur.com/SYx6p.jpg


Source: (StackOverflow)

Best resolution resizing image using ImgScalr

I am very new to ImgScalr API.I need to resize my images to different views, one of them being a mobile view and second a thumbnail view. I have made use of the resize method, but have a doubt. Which is the best of the resize method to resizing the image out of the multiple options available that keeps the proper aspect ratio(as in the image doesnt become blurred)

One thing I noticed was that every resize method takes in a targetSize argument. How does specifiying this field make sure that the aspect ratio of the image does not get affected.

What should the ideal arguments to the resize method be, given that I need to generate a 2 KB thumbnail view of my input image that may be of size of around 2 MB.

I am a bit confused because of the lack of enough documentation and examples.


Source: (StackOverflow)

Out of memory Exception while dealing with images. in java

==================Hi here is the mycode ==============================

this is example to

imgscalr

package anil1.main;

import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageFilter;
import java.io.File;

import javax.imageio.ImageIO;

import org.imgscalr.Scalr;

import static org.imgscalr.Scalr.*;

public class ImageScalar {
    public static void thum(String img) throws Exception
    {

         String path1 = "."; 

          String files;
          File folder = new File("C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\webapps\\Myapp\\images\\candidates");
          File[] listOfFiles = folder.listFiles(); 

          for (int i = 0; i < listOfFiles.length; i++) 
          {

           if (listOfFiles[i].isFile()) 
           {
           files = listOfFiles[i].getName();
               if (files.endsWith(".jpg") || files.endsWith(".png") || files.endsWith(".jpeg")|| files.endsWith(".JPEG") )
               {

            boolean token =false;
        String path=listOfFiles[i].getPath();

        BufferedImage originalImage = ImageIO.read(new File(path));


    //  BufferedImage thumbnail =Scalr.crop(originalImage, 140, 140, 140, 140);

        BufferedImage thumbnail=Scalr.resize(originalImage, Scalr.Method.ULTRA_QUALITY,Scalr.Mode.FIT_EXACT, 180, 250);




        String parent = "C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\webapps\\Myapp";
        String child = "\\Thumbs\\images\\candidates";



    String  total=parent+child+path.substring(path.lastIndexOf("\\"));
    String  total1=parent+child;
    System.out.println(total);

    File f=new File(total1);
    File f1=new File(path);
    File f2=new File(total);
    try{
        if(f1.exists()){
        if(f.exists())
        {

            System.out.println("from if");
        ImageIO.write(thumbnail, "jpeg", f2);

        }
        else 
        {
            System.out.println("from else");
            f.mkdirs();
        ImageIO.write(thumbnail, "jpeg", f2);

        }}
        if (new File(total1).exists())
        token=true;

        System.out.println(token);

               }finally{
                   originalImage.flush();  
                   thumbnail.flush();
                f=null;   
                f1=null;
                thumbnail=null;
                originalImage=null;
               }
             }//if
          }//for
    }//main

    }//class




public static void main(String[] args)throws Exception {
    thum("");
}
}

after processing some images i got following exception

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.awt.image.DataBufferInt.<init>(Unknown Source)
    at java.awt.image.Raster.createPackedRaster(Unknown Source)
    at java.awt.image.DirectColorModel.createCompatibleWritableRaster(Unknown Source)
    at java.awt.image.BufferedImage.<init>(Unknown Source)
    at org.imgscalr.Scalr.createOptimalImage(Scalr.java:2006)
    at org.imgscalr.Scalr.scaleImage(Scalr.java:2133)
    at org.imgscalr.Scalr.scaleImageIncrementally(Scalr.java:2275)
    at org.imgscalr.Scalr.resize(Scalr.java:1711)
    at anil1.main.ImageScalar.thum(ImageScalar.java:40)
    at anil1.main.ImageScalar.main(ImageScalar.java:114)

i am unable find out solution can any one help to me?


Source: (StackOverflow)

Determine the size of an image using ImgScalr

Hi I am currently using ImgScalr library and I have few markers to download images from an HTML document , however sometimes the images are of low quality,and if they are then I need to scan thru the html source to download all the images and use the one with the biggest size in bytes.

I use ImgScalr library, I need to know how I can check the size of the image in bytes to determine if it meets my quality requirements. Is it the right approach?

Thanks.


Source: (StackOverflow)