 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert Image to Byte Array in java?
Java provides ImageIO class for reading and writing an image. To convert an image to a byte array –
- Read the image using the read() method of the ImageIO class.
- Create a ByteArrayOutputStream object.
- Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class.
- Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
Example
import java.io.ByteArrayOutputStream; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ImageToByteArray { public static void main(String args[]) throws Exception{ BufferedImage bImage = ImageIO.read(new File("sample.jpg")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bImage, "jpg", bos ); byte [] data = bos.toByteArray(); } }Advertisements
 