Java image from byte

Как преобразовать байт[] в буферизованное изображение в Java

В этой статье показано, как преобразовать “байт[]” в “буферизованное изображение” в Java.

В этой статье показано, как преобразовать байт[] в Буферизованное изображение на Java.

InputStream is = new ByteArrayInputStream(bytes); BufferedImage bi = ImageIO.read(is);

Идея заключается в том, чтобы поместить байт[] в объект ByteArrayInputStream , и мы можем использовать ImageIO.прочитайте , чтобы преобразовать его в буферизованное изображение .

1. Преобразуйте байт[] в буферизованное изображение.

В приведенном ниже примере показано, как преобразовать Буферизованное изображение в байт [] и наоборот.

package com.mkyong.io.image; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; public class ImageUtils < public static void main(String[] args) throws IOException < Path source = Paths.get("c:\\test\\mkyong.png"); Path target = Paths.get("c:\\test\\mkyong-new.png"); BufferedImage bi = ImageIO.read(source.toFile()); // convert BufferedImage to byte[] ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "png", baos); byte[] bytes = baos.toByteArray(); // convert byte[] back to a BufferedImage InputStream is = new ByteArrayInputStream(bytes); BufferedImage newBi = ImageIO.read(is); // add a text on top on the image, optional, just for fun Graphics2D g = newBi.createGraphics(); g.setFont(new Font("TimesRoman", Font.BOLD, 30)); g.setColor(Color.BLACK); g.drawString("Hello World", 100, 100); // save it ImageIO.write(newBi, "png", target.toFile()); >>

Скачать Исходный Код

Рекомендации

  • Изображение Javax
  • Преобразование файлов в массивы байтов на Java
  • Как изменить размер изображения в Java
Читайте также:  Php xml перенос строки в

Источник

Convert Byte Array to BufferedImage in Java

Convert byte array to BufferedImage in java

In this article, we will see how to convert byte array to BufferedImage in java.

💡 Outline

To convert byte array to BufferedImage, you can use below code:

Convert byte array image to BufferedImage in java

Using ByteArrayInputStream

Here are steps to convert byte array to BufferedImage in java.

  • Create ByteArrayInputStream object by passing byte[] in the constructor.
  • Pass above InputStream to ImageIo.read() and get BufferedImage from it.

public static BufferedImage convertByteArrayToBufferedImage ( byte [ ] byteArr ) throws IOException

[email protected]: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = [email protected] transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 500 height = 500 #numDataElements 3 dataOff[0] = 2

Using BufferedImage’s setData

Above approach may not work in some case and may return null.

You can follow below steps to use this method as per this stackoverflow thread.

  • Create a blank image
  • Transform byte array to Raster and use setData to fill the image

public static BufferedImage convertByteArrayToBufferedImage ( byte [ ] byteArr ) throws IOException

Raster raster = Raster . createRaster ( bufferedImage . getSampleModel ( ) , new DataBufferByte ( byteArr , byteArr . length ) , new Point ( ) ) ;

That’s all about how to convert byte array to BufferedImage in java.

Was this post helpful?

Share this

Author

Count Files in Directory in Java

Count Files in Directory in Java

Table of ContentsUsing java.io.File ClassUse File.listFiles() MethodCount Files in the Current Directory (Excluding Sub-directories)Count Files in the Current Directory (Including Sub-directories)Count Files & Folders in Current Directory (Excluding Sub-directories)Count Files & Folders in Current Directory (Including Sub-directories)Use File.list() MethodUsing java.nio.file.DirectoryStream ClassCount Files in the Current Directory (Excluding Sub-directories)Count Files in the Current Directory (Including Sub-directories)Count […]

Convert System.nanoTime to Seconds in Java

Table of ContentsIntroductionSystem.nanoTime()Dividing the System.nanoTime() with a Constant ValueUsing the convert() Method of Time Unit Class in JavaUsing the toSeconds() Method of Time Unit Class in JavaUsing the Utility Methods of Duration Class in Java Introduction In this article, we will look into How to Convert System.nanoTime() to Seconds in Java. We will look at […]

Update Value of Key in HashMap in Java

Table of ContentsUsing the put() Method of HashMap Collection in JavaUsing the compute() Method of HashMap Collection in JavaUsing the merge() Method of the HashMap Collection in JavaUsing the computeIfPresent() Method of The HashMap Collection in JavaUsing the replace() Method of The HashMap Collection in JavaUsing the TObjectIntHashMap Class of Gnu.Trove Package in JavaUsing the […]

Читайте также:  Php find classes in folder

How to Get Variable From Another Class in Java

Table of ContentsClasses and Objects in JavaAccess Modifiers in JavaGet Variable From Another Class in JavaUsing the Default or Public Access Modifier of the Other ClassUsing the Static Member of Another ClassUsing the Inheritance Concept of JavaUsing the Getters and Setters of Another ClassUsing the Singleton Pattern Design for Declaring Global VariablesConclusion In this article, […]

Create Array of Linked Lists in Java

Table of ContentsIntroductionLinked List in JavaApplication of Array of Linked ListsCreate Array of Linked Lists in JavaUsing Object[] array of Linked Lists in JavaUsing the Linked List array in JavaUsing the ArrayList of Linked Lists in JavaUsing the Apache Commons Collections Package Introduction In this article, we will look at how to Create an Array […]

Check if Date Is Between Two Dates in Java

Table of ContentsIntroductionDate & Local Date Class in JavaCheck if The Date Is Between Two Dates in JavaUsing the isAfter() and isBefore() Methods of the Local Date Class in JavaUsing the compareTo() Method of the Local Date Class in JavaUsing the after() and before() Methods of the Date Class in JavaUsing the compare To() Method […]

Источник

How to convert Byte Array to Image in java with easy example

This is a Java tutorial on how to convert Byte array to image in Java. In my previous Java tutorial, I have shown you How to convert an image to byte array in Java
So I am again with this new tutorial. This time you will be given a Byte array and you will have to convert it to an Image using Java.

Читайте также:  Http webtutor letoile ru view doc html mode default

Java has its own ImageIO class so that we can read and write images in Java. In order to convert a byte array to an image we need to follow these following steps:

  • Create a ByteArrayInputStream object.
  • Read the image. ( using the read() method of the ImageIO class )
  • Finally, Write the image. ( using the write() method of the ImageIO class )

Convert Byte Array to Image in Java

Take a look at the following example:

import java.io.*; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class Codespeedy < public static void main(String[] args) throws Exception < BufferedImage buffered_image= ImageIO.read(new File("myfile.jpg")); ByteArrayOutputStream output_stream= new ByteArrayOutputStream(); ImageIO.write(buffered_image, "jpg", output_stream); byte [] byte_array = output_stream.toByteArray(); ByteArrayInputStream input_stream= new ByteArrayInputStream(byte_array); BufferedImage final_buffered_image = ImageIO.read(input_stream); ImageIO.write(final_buffered_image , "jpg", new File("final_file.jpg") ); System.out.println("Converted Successfully!"); >>

If everything goes fine, the output will be like this:

Methods and classes:

ImageIO.write() – This method writes an image file.

ByteArrayOutputStream – This class holds a copy of data so that it can forward it later to multiple streams easily.

Источник

Конвертация изображения в байтовый массив в Java и наоборот

Как преобразовать массив байтов в изображение в Java?

Java предоставляет класс ImageIO для чтения и записи изображения. Для того, чтобы преобразовать массив байтов в изображение на Java.

  • Создайте объект ByteArrayInputStream, передав байтовый массив (который должен быть преобразован) в его конструктор.
  • Прочитайте изображение, используя метод read() класса ImageIO (передав ему объекты ByteArrayInputStream в качестве параметра).
  • Наконец, запишите изображение, используя метод write() класса ImageIo.

Пример

import java.io.ByteArrayOutputStream; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ByteArrayToImage < 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(); ByteArrayInputStream bis = new ByteArrayInputStream(data); BufferedImage bImage2 = ImageIO.read(bis); ImageIO.write(bImage2, "jpg", new File("output.jpg") ); System.out.println("image created"); >>

Средняя оценка 3.1 / 5. Количество голосов: 9

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

Оцените статью