Wednesday, 21 December 2011

Java Spring image handling with base64 encoding

There are numerous ways to handle images in java. Whenever the approach is to create image from database, without creating image on disk and if you want everything should be in-memory then, following approach can be used with apache Base64 encoding.

Steps:
1) Add enctype="multipart/form-data" to form tag.
2) Add input type file to form which gives the  "org.springframework.web.multipart.commons.CommonsMultipartFile" object which inturn gives the byte array and also add code to preview the image as:


<div id='preview' style="width:600px">
        Upload your image <input id="content" type='file' name="content" onchange="previewImage(this);" />
          <br>
         <img id="pImage" src="#" />
 </div>

<script>
 function previewImage(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#pImage').attr('src', e.target.result);
            $('#pImage').attr('width', 140);
            $('#pImage').attr('height', 120);
          };
        //console.log('file name ' + input.files[0])
        reader.readAsDataURL(input.files[0]);
    }
}
</script>

3) In code you can create the image to required width, height and other dimensions..The example API is:

....
import net.sf.fir4j.generator.transform.Transformation;
import net.sf.fir4j.options.OutputOptions;
import net.sf.fir4j.options.RenderMode;
import net.sf.fir4j.options.ResizeMode;
import net.sf.fir4j.options.OutputOptions;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
 ......
private static string  DEFAULT_IMAGE_EXTENSION = "jpg";
public byte[] generateImage(byte[] argContent, String argExtension) {
        if (argContent != null) {
            InputStream bis = null;
            ByteArrayOutputStream bos = null;
            try {
                bis = new ByteArrayInputStream(argContent);
                bos = new ByteArrayOutputStream();
                BufferedImage image = ImageIO.read(bis);
                BufferedImage bImage = generateImage(image, this.options);
                String extension = argExtension;
                if (StringUtils.isEmpty(argExtension)) {
                    extension = DEFAULT_IMAGE_EXTENSION;
                }
                ImageIO.write(bImage, extension, bos);
                bos.flush();
                byte[] scaledImageBytes = bos.toByteArray();
                return scaledImageBytes;
            } catch (Exception e) {
                logger.error(
                        "Error occurred while regenerating image from database byte contents:",
                        e);
            } finally {
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (Exception e) {
                        // ignore.
                    }
                }
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (Exception e) {
                        // ignore.
                    }
                }
            }
        }
        return null;
    }

 public BufferedImage generateImage(final BufferedImage argImage,
            OutputOptions argOptions) {                              
           Transformation transformation = new CropTransform(argImage, argOptions);
           return transformation.generateImage();
}

In above code "BufferedImage" is java.awt.image.BufferedImage;
From above method you get the byte array after applying the required options. In above code "this.options" specifies the required options as:
.....
private options OutputOptions();
// it is from firj4.jar
        this.options = new Options();
        this.options.setQuality(1);
        this.options.setRenderMode(RenderMode.BEST);
        this.options.setMode(ResizeMode.resizeAndFill);
        this.options.setMaxWidth(argWidth);
        this.options.setMaxHeight(argHeight);

Once you get the byte array, you can easily store it in database.

4) Get the bytes from database, encode using apache Base64, create the string which we can pass. Set the generated string to src attribute of img tag.

Load the object from database using hibernate or with whatever mechanism you have. Once you get the object say "image", get the byte array, say "content".


......
import org.apache.commons.codec.binary.Base64;

.....
String str = "data:image/png;base64,"
                        + new String(Base64.encodeBase64(content,
                                false));

Now, set this str to form bean object and simpy use it in UI for "src" attribute of "img" tag..That's it ;)



Monday, 17 October 2011

An inspiration to each and every one

Agneepath Agneepath Agneepath

Vriksh ho bade bhale,
ho gane ho bhale,
Ek patra chhah bhi mang mat, mang mat, mang mat,
Agneepath, Agneepath, Agneepath...

Tu na thame ga kabhi, 
Tu na mude ga kabhi,
Tu na rukega kabhi,
Kar shapath, Kar shapath, Kar shapath,
Agneepath, Agneepath, Agneepath...

Ye maha drushya hai,
Chal raha manushya hai,
Ashru, sweth, rakth se latpath, latpath latpath,
Agneepath, Agneepath, Agneepath...

--Harivansh Rai Bachchan

Sunday, 4 September 2011

Does marks sheet really justify the capability of a person


My first post. Feels good to do something new and write something new. One more step to improve myself ;-). Since it's my first, I choose to write some general topic. Next time, I'll pick some specific topic (May be related to my profession).

I was watching F.A.L.T.U the other night which inspired me to write this. One of the F.A.L.T.U (So am I), said a dialogue – If everyone needs more than 70% then why do we have 35% as pass-out cut. Where the guys between 35% to 70% do has to go?

Are the marks only way to judge the capability of student? I am sure if we have a survey, most of the people will say no as the answer. In that case, why do the great big software companies need only people with percentage above 70% and that too with consistency.  Until and unless your resume has the good marks, your resume will not even be considered. Why?

Marks cannot be only considered as the only way to judge the students. The highest mark sheet depicts the attitude, sincerity, hard work, dedication of students. Does it mean that less mark sheet doesn’t show these things in a student? A person with less mark sheet might too have great dedication towards his studies and work.

In this fast pace world, at the initial stage more than 90% of students strive only for exceptional marks. The society, the parents and so called corporate colleges are responsible for this. Talking about these colleges, these are really abysmal. When you force a student to put in writing an essay or a problem from early morning to late night, obviously it will be register in the brain. In this way, can a student be educated? 

Let me tell you an incident here in this context. I have a cousin who just finished her +2 and her father met me and asked can you suggest me what would be good to her. I said instead-of asking me or anyone else, why don’t you ask her first.  Eventually, I asked her and she replied, I just want to do what my parents want me to do. I do agree that we should respect the parents and at the same time, it doesn’t mean that you shouldn’t raise your point. This will make things much clear to both entities. It’s better to put your point initially instead-of feeling later, I wish I could change it. And it is not surprising that later point of time few people even commit suicide, which is the most stupidity act. Life is really precious. Understand the value of it.

As a student, you should be clear about your goals and achievements. If you have the confidence to do it, you can easily convince parents and others about your choice. Having said that, let me append, at that young age you might think of something and as you grow older and progress in life, you might choose something different which is superior for your future, like in my case (Please don’t ask me what it is. That’s not the important here :-)). I thought of something in my childhood and now I am something. Nothing to be bothered. I am happy with what I am and where I am and I know, still a long way to go and do much more things in life. As Peter Parker (Spider man) quoted – There is always a choice. It’s we, who choose it. 

Marks should be only considered as a potential of a student. Marks are not the only way to judge the ability of a student. If that’s the case, needless to mention about the great Dhuru bai Ambani, Sachin Tendulkar, M.S. Dhoni etc. One needs to consider the sincerity, dedication, hard work and abilities. How to show these things? That’s where your attitude comes into picture. The mind-set needs to be understood first. That’s really not an easy task since we cannot guarantee what would be the future thoughts. In fact, I think, no can judge anyone. We can only have an opinion on someone. The opinion should not guide to the judgment. 

As far as I know, there are three important things in life which I learned from my boss. Learning, understanding and applying what you have learned. If an education system or civilization cannot facilitate with these things, nothing can be achieved.  Everyone should strive to work hard to achieve the goals. Each and every day has something new to educate. Nothing is impossible and nothing is easy. It's depends on us, how we take it.

With this, I conclude my first post. I am not against or with something or someone. I sincerely apologize, if I hurt someone. I just wanted to put my thoughts in words. I did it. Hope people do like it ;-)