In Java, image and byte[] convert each other

Source: Internet
Author: User

In Java, image and byte[] convert to each other hateful ... It's pretty good, actually.
Just write down the things that are hard to come up with, afraid to forget ...
Next, let me introduce a simple byte[] to image,
We only need a binary string (byte[]) that stores the image information.
Then, this:
InputStream Buffin = new Bytearrayinputstream (/* Binary string */,
/* Start position */,
/* Binary string length */));

BufferedImage img = imageio.read (Buffin);
In this way, we have a can output bufferedimage, is not very simple ~
Next, we'll write a piece of code, and it's simple.
First, we have to prepare an image object that can be output.
Then, this


Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
Imageio.write ((renderedimage)//The format of the picture */,/* picture to output */,bos);(to use try and Chatch


Then use Bos.tobytearray ();(Bytearrayoutputstream.tobytearray) to get the desired byte[] ~
Isn't it very simple?
I just wanted to upload it.
Picture, create a new picture of the specified size and then store it together in the database.
It was not easy to use the Toolkit class to generate a picture of what, is said to be Java.awt.image.TookitImage object


Excerpted from Http://blog.csdn.net/comcow/archive/2008/10/08/3031252.aspx

Add one more word.
Image Img=toolkit.getdefaulttoolkit (). CreateImage (buf, 0,buf.length);

InputStream conversion byte[]
Public byte[] Tobarray (InputStream is)
{
Bytearrayoutputstream OUTP = new Bytearrayoutputstream ();
int ch = 0;
while ((Ch=is.read ())!=-1)
Outp.write (CH);
Byte[] B = Outp.tobytearray ();
return b;
}

In Java, image and byte[] convert each other

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.