Reading PNG file from the stream - java

I trying to build RDP application for android mobile.so in server side i am sending the png images with the robot class, but in client side i am not able to read that messages and print them on my android device.
i am using following code to read the JPEG file body data and i am able to show those images
InputStream in = sock.getInputStream();
while(true)
{
byte[] bytes = new byte[1024*1024];
int count = 0;
do
{
count+= in.read(bytes,count,bytes.length-count);
}
while(!(count>4&&bytes[count-2]==(byte)-1 && bytes[count-1]==(byte)-39));
}
can any one help me how to read the png file out of the inputstream.

Try this
BufferedInputStream in = new BufferedInputStream(sock.getInputStream());
BufferedImage image = ImageIO.read(in);

Related

How to send picture into Discord Channel

I need to send picture (screenshot) into Discord channel. I have successfully developed text sending into channel but I do not know how to send a screen.
Here is part of my code:
// connection to the Channel
TextChannel channel = api.getTextChannelById(this.channelId);
if (channel != null) {
channel.sendMessage(pMessage).queue();
}
// capture the whole screen
BufferedImage screencapture = new Robot().createScreenCapture( new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );
// Save as JPEG - not necessary
File file = new File("screencapture.jpg");
ImageIO.write(screencapture, "jpg", file);
// CODE for sendPicture (screencapture to the Channel) HERE!!!
// code here
// code here
Any idea how to do it?
As per the JDA docs, to send a file to a channel, you should use the appropriate sendFile RestAction.
There's a range of different send methods you may use, some of which allow you to send a message along with your file.
As an example, to send a file by using a File object:
channel.sendFile(new File("path/to/file")).queue();
Or, directly with an InputStream (in your case - to avoid writing to disk).
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(screencapture, "jpg", stream);
channel.sendFile(stream.toByteArray(), "fileName.jpg").queue();

Trying to read image blob from oracle DB with ImageIO.read in Java not working [duplicate]

This question already has answers here:
Can't read and write a TIFF image file using Java ImageIO standard library
(5 answers)
Closed 4 years ago.
I have some images stored in an oracle DB as blobs. I want to read them and display in a JLabel. After reading them, I have tried using ImageIO.read but it always returns null. See my code below:
Blob blob = rs.getBlob(2);
BufferedImage frontImg = ImageIO.read(blob.getBinaryStream());
lblFrontImage.setIcon(new ImageIcon(frontImg));
I am able to save the image to a file however using the following code so I know the image is valid:
Blob blob = rs.getBlob(2);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream("test.jpg");
byte[] buff = new byte[4096];
int len = 0;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
out.close();
Other ways I have tried to display the image in a JLabel
byte[] frontBytes = rs.getBytes(2);
BufferedImage frontImg = ImageIO.read(new
ByteArrayInputStream(fileContent));
lblFrontImage.setIcon(new ImageIcon(frontImg));
And
byte[] frontBytes = rs.getBytes(2);
BufferedImage image;
ByteArrayInputStream bis = new ByteArrayInputStream(frontBytes);
image = ImageIO.read(bis);
bis.close();
lblFrontImage.setIcon(new ImageIcon(image));
Also
InputStream in = blob.getBinaryStream();
image = ImageIO.read(in);
byte[] frontImgBytes = blob.getBytes(1, (int) blob.length());
System.out.println("front bytes length: ====\n" + frontImgBytes.length);
BufferedImage frontImage = ImageIO.read(new
ByteArrayInputStream(frontImgBytes));
lblFrontImage.setIcon(new ImageIcon(frontImage));
Tried a lot of ways, just keep getting java.lang.NullPointerException. No other exception or error. Any help will be greatly appreciated.
I finally realised it was because the images were TIFF images. I couldn't use the default ImageIO libraries. I noticed another StackOverflow thread here Can't read and write a TIFF image file using Java ImageIO standard library and used your twelvemonkeys libraries #haraldK and it worked fine. Thanks a lot.

Read image and send it via socket - could not open file

I am trying to write a simple server that uses sockets and reads images from disc when it receives http request from browser.
I am able to receive the request, read the image from disc and pass it to the browser (the browser then automatically downloads the image). However, when I try to open the downloaded image, it says:
Could not load image 'img.png'. Fatal error reading PNG image file: Not a PNG file
The same goes for all other types of extensions (jpg, jpeg, gif etc...)
Could you help me out and tell me what am I doing wrong? I suspect that there might be something wrong with the way I read the image or maybe some encoding has to be specified?
Reading the image from disc:
// read image and serve it back to the browser
public byte[] readImage(String path) {
File file = new File(FILE_PATH + path);
try {
BufferedImage image = ImageIO.read(file); // try reading the image first
// get DataBufferBytes from Raster
WritableRaster raster = image.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return data.getData();
} catch (IOException ex) {
// handle exception...
}
return ("Could not read image").getBytes();
}
Writing the data via socket:
OutputStream output = clientSocket.getOutputStream();
output.write(result);
In this case, the result contains the byte array produced by the readImage method.
EDIT: second try with reading the image as normal file
FileReader reader = new FileReader(file);
char buf[] = new char[8192];
int len;
StringBuilder s = new StringBuilder();
while ((len = reader.read(buf)) >= 0) {
s.append(buf, 0, len);
byte[] byteArray = s.toString().getBytes();
}
return s.toString().getBytes();
You may use ByteArrayOutputStream, like,
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", byteArrayOutputStream);
and then you can write to socket as,
outputStream.write(byteArrayOutputStream.toByteArray());

Trying to compress images (Gzip+Jpeg) and then uncompress them

I am trying to compress a sequence of images in png format. It seems that compression is going well:
FileOutputStream fos = null;
GZIPOutputStream gzip = null;
fos = new FileOutputStream(PATH_SAVE_GZIP);
gzip = new GZIPOutputStream(fos);
for (int i = 0; i < NB_OF_IMAGES; i++) {
BufferedImage im = images.get(i).getBufImg();
ImageIO.write(im, "JPEG", gzip);
}
gzip.finish();
gzip.close();
fos.close();
However I get Exception Nullpointer... when I try to uncompress it with this code.
What am I'm doing wrong?
I've finished my project and now I know the answer. This could be solved by several ways:
One is by using ObjectOutput/Input Stream and write BufferedImages like objects.
The other is to use ByteArrayOutputStream and write images like bytes. Prior to use this you should know the size to be written. So I've solved this writing size before each image. Not efficient way... However works.
fileOutputStream fos = new FileOutputStream(path);
GZIPOutputStream gzip = new GZIPOutputStream(fos);
gzip.write(shortToBytes(numImatges));
gzip.write(shortToBytes((short) 0));
for (int i = 0; i < dates.getNB_OF_IMAGES(); i++) {
if (images != null) {
im = images.get(i).getBufImg();
}
ByteArrayOutputStream byteOstream = new ByteArrayOutputStream();
ImageIO.write(im, "jpeg", byteOstream);
byteOstream.flush();
byteOstream.close();
gzip.write(shortToBytes((short) byteOstream.size()));
gzip.write(byteOstream.toByteArray());
}
//close streams
Your problem is that you write all the images to a single GZIP stream and when reading, ImageIO doesn't know where one image ends and the next begins.
You got two options:
Use ZIP instead of GZIP
Package the files in a TAR file using jtar or Java Tar Package and then GZIP the tar, when reading you will first UnGZIP and then extract the images from the tar file

Transfer Image (*.jpeg, *.png etc) file from client to server

In my java application I want to transfer some Images from client to server.
I am using Socket to connect client with server.
It is working when I transfer string from client to server but I am not able to transfer Image file.
I am using
BufferedInputStream
BufferedOutputStream
for transferring string.
I know for transferring file I need to use FileInputStream as:
BufferedInputStream bis bis = new BufferedInputStream(new FileInputStream("111.JPG"));
But I don't know, what exactly I need to write.
so please give your answer by some sample of code.
You should convert image to byte.
You can use this function.
static byte[] ImageToByte(System.Drawing.Image iImage)
{
MemoryStream mMemoryStream = new MemoryStream();
iImage.Save(mMemoryStream,
System.Drawing.Imaging.ImageFormat.Gif);
return mMemoryStream.ToArray();
}
And you can call this function in your server program.
Bitmap tImage = new Bitmap(Image URL goes here);
byte[] bStream = ImageToByte(tImage);
while (true)
{
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected");
while (client.Connected)
{
NetworkStream nStream = client.GetStream();
nStream.Write(bStream, 0,
bStream.Length);
}
}
There are many examples on the internet already:
here
here
etc.
Please consider using google next time.

Categories

Resources