How to send picture into Discord Channel - java

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();

Related

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());

Java Image Server: socket write error

A couple of days ago I thought about programming my own image client to transfer images directly via the HTTP. I googled and researched quite some time and wrote my server:
public class SConnection extends Thread {
Socket client;
/* ... */
#Override
public void run() {
while(true) {
try {
//Get some image paths
File folder = new File(new java.net.URI("file:///C:/images/"));
File[] images = folder.listFiles();
//Load the image
BufferedImage bi = ImageIO.read(images[0]);
//Write the image
ImageIO.write(bi, "JPEG", client.getOutputStream());
} catch (Exception ex) {
ex.printStackTrace();
return;
}
}
}
The main class is a Thread waiting to accept many connections, storing them in an ArrayList, creating instances of SConnection and starting them.
The client looks like this:
URL target = new URL("http://127.0.0.1:82"); //The server - so far, so good
URLConnection conn = target.openConnection();
BufferedImage in = ImageIO.read(conn.getInputStream()); //And as I try to receive the image: boom, exception
File save = new File(new java.net.URI("file:///C:/images/result.jpeg"));
ImageIO.write(in, "JPEG", save);
Server and client both send Exceptions located at the ImageIO.write / ImageIO.read - lines.
The server says:
java.net.SocketException: Connection reset by peer: socket write error
The client says:
java.io.IOException: Invalid Http response
I get, that the image is not transferred correctly, but what should I change? Any clues?
Thanks you guys, in advance!
You don't appear to be writing HTTP headers, so the client URLConnection won't understand the reply and will close the connection, causing 'connection reset by peer' at the sender.
You don't need to construct a URI to open a file.
You don't need to use ImageIO at all. This just wastes time and space. Just copy the bytes, like any other file type.
In short you don't really need this code at all. The default servlet will do it for you.

Reading PNG file from the stream

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);

File transfer and object serialization in Java

Im working on a Client/server chat application which allows user to send files (images / videos...) through a socket connection.
In order to manage all kind of communication, I use an Object "Packet" which stores all information that I want to send. (Sender, receivers, file ...).
Here is a code sample where I write in the stream :
private void write(Packet packet) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(packet);
this.outStream.write(bos.toByteArray());
}
And outStream is an OutputStream.
Here is my Connection run :
public void run() {
while (isRunning()) {
try {
byte[] buffer = new byte[65536];
// Read from the InputStream
inStream.read(buffer);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer));
Packet p = (Packet) in.readObject();
} catch (IOException e) {
e.printStackTrace();
this.disconnect();
}
}
}
It works very well for all purpose except files transfer !
I put the file in a byte[] (with filestream) and store the array in my Packet Object.
When the server receive the communication it breaks on the "in.readObject()" and give me a pretty "java io streamcorruptedexception wrong format : 0" exception.
I tried the transfer with a custom byte[] (filled by a string.getBytes()) and it worked very well.
So, what am I doing wrong ?
You're reading from the InputStream to a byte array (with an arbitrary size which could be too small). Then you construct an ObjectInputStream to read from this byte array. Why don't you read your object directly from the InputStream?
ObjectInputStream in = new ObjectInputStream(inStream);
Packet p = (Packet) in.readObject();
No need for a buffer.
Moreover, InputStream.read() doesn't read everything from the InputStream. It reads what is available, and returns the number of bytes read. If you don't loop until it returns -1, you only read a part of what has been sent on the other side.
BTW, you're doing the same mistake on the sending side. Instead of writing your object directly to the output stream, you write it to a byte array, adn then send this byte array. Write your object directly to the stream:
ObjectOutputStream os = new ObjectOutputStream(this.outputStream);
os.writeObject(packet);
No need for a buffer.

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