How to display Base64 string in image on Java com.sun.net.httpserver.HttpServer ?
I run this code:
static class base implements HttpHandler{
#Override
public void handle(HttpExchange he) throws IOException {
byte[] name = Base64.getEncoder().encode(base64String.getBytes());
byte[] decodedString = Base64.getDecoder().decode(new String(name).getBytes("UTF-8"));
String base64String = "BASE64 IMAGE";
Headers headers = he.getResponseHeaders();
headers.add("Content-Type", "image/png");
File file = new File ("1.png");
//System.out.println(file);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream bufferedInputStream = new ByteArrayInputStream(decodedString);
bufferedInputStream.read(decodedString, 0, decodedString.length);
he.sendResponseHeaders(200, decodedString.length);
final OutputStream os = he.getResponseBody();
os.write(decodedString);
os.close();
}
}
But displays a white cube
Related
I'm not able to convert pdf file to base64 string but file uploaded successfully when I open pdf file it showing 0kb file size. This same code works for an image but when I try to use to convert for pdf file it is not working. in my code I have created a method called 'NewBase64' in that I'm converting pdf file to base64 can any tell me where I'm gone wrong plz help me.
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private int PICK_IMAGE_REQUEST = 1;
VolleyAppController volleyAppController;
mydb db;
public static String url = "http://xxx.xxx.x.x:xx/Android_Service.asmx/UploadPDFFile";
int SELECT_MAGAZINE_FILE = 1;
private File myFile;
String encodeFileToBase64Binary = "";
private String NewBase64(String Path) {
String encoded = "";
try {
File file = new File(Path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos = new ObjectOutputStream(bos);
oos.writeObject(file);
bos.close();
oos.close();
byte[] bytearray = bos.toByteArray();
encoded = Base64.encodeToString(bytearray, Base64.DEFAULT);
} catch (Exception ex) {
}
return encoded;
}
private void uploadImage() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String image = null;
image = NewBase64(encodeFileToBase64Binary);
String name1 = name.getText().toString().trim();
Map<String, String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name1);
return params;
}
};
}
You can convert PDF to base64 using below method
public String NewBase64(File mfile) {
ByteArrayOutputStream output = null;
try {
InputStream inputStream = null;
inputStream = new FileInputStream(mfile.getAbsolutePath());
byte[] buffer = new byte[8192];
int bytesRead;
output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
} catch (IOException e) {
e.printStackTrace();
}
return output.toString();
}
In my app I'm zipping and then downloading larges files, the files are located in azure, so I read the files from a stream and then zip them one after another, so I can dowload the zip file after all files has been zipped, here's my code:
#RequestMapping(value = "{analyseId}/download", method = RequestMethod.GET, produces = "application/zip")
public ResponseEntity<Resource> download(#PathVariable List<String> paths) throws IOException {
String zipFileName = "zipFiles.zip";
File zipFile = new File(zipFileName);
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String path : paths) {
InputStream fis = azureDataLakeStoreService.readFile(path);
addToZipFile(path , zos, fis);
}
zos.close();
fos.close();
BufferedInputStream zipFileInputStream = new BufferedInputStream(new FileInputStream(zipFile.getAbsolutePath()));
InputStreamResource resource = new InputStreamResource(zipFileInputStream);
zipFile.delete();
return ResponseEntity.ok()
.header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + zipFileName)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}
private static void addToZipFile(String path, ZipOutputStream zos, InputStream fis) throws IOException {
ZipEntry zipEntry = new ZipEntry(FilenameUtils.getName(path));
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
However on azure the request time out is set to 230 sec, and cannot be changed, however for big files it takes more than that to load and then zip the files on the server, so the connection with the client will be lost meanwhile.
So my question is since I'm getting the data from a stream, can we do all these operations simultaneously, means getting the stream and download it as the same time and not waiting till getting the whole file, or if there any other idea can any body share it here please.
Thanks.
The answer is to not download the file to the server and then send it to the client but streaming it to the client directly here's the code
#RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody download(#PathVariable String path) throws IOException {
final InputStream fecFile = azureDataLakeStoreService.readFile(path);
return (os) -> {
readAndWrite(fecFile, os);
};
}
private void readAndWrite(final InputStream is, OutputStream os)
throws IOException {
byte[] data = new byte[2048];
int read = 0;
while ((read = is.read(data)) >= 0) {
os.write(data, 0, read);
}
os.flush();
}
I also added this configuration to ApplicationInit:
#Configuration
public static class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(-1);
configurer.setTaskExecutor(asyncTaskExecutor());
}
#Bean
public AsyncTaskExecutor asyncTaskExecutor() {
return new SimpleAsyncTaskExecutor("async");
}
}
I have the following code which works for text files but doesn't work for pdf files. My files contain english and greek characters. I try to convert a pdf file to byteStream and the byteStream to String format in order to save it in database. After this I try to create the pdf from the saved String.
Any help?
public class PdfToByteStream {
public static byte[] convertDocToByteArray(String path)throws FileNotFoundException, IOException{
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
} catch (IOException ex) {
Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
return bytes;
}
public static void convertByteArrayToDoc(String path, byte[] bytes)throws FileNotFoundException, IOException {
File someFile = new File(path);
FileOutputStream fos = new FileOutputStream(someFile);
fos.write(bytes);
fos.flush();
fos.close();
}
public static void main(String[] args) throws FileNotFoundException, IOException {
byte[] bytes = convertDocToByteArray("path/test.pdf");
String stream = new String(bytes, "UTF-8");//ok for txt
byte[] newBytes = stream.getBytes(Charset.forName("UTF-8")); // ok for txt
convertByteArrayToDoc("path/newTest.pdf", newBytes);
}
}
If you use Base64 encoding you will be able to convert the PDF to a string and back.
Here is the relevant part of the code which needs to be changed:
import java.util.Base64;
...
public static void main(String[] args) throws FileNotFoundException, IOException {
byte[] bytes = convertDocToByteArray("some.pdf");
String stream = Base64.getEncoder().encodeToString(bytes);
byte[] newBytes = Base64.getDecoder().decode(stream);
convertByteArrayToDoc("some_new.pdf", newBytes);
}
I have trouble to sending data from Android Client to NodeJS Server.
I use Socket.IO-client java library in my client.
But, there is not much information for me.
How can i sending binary data from android client to nodejs server?
You can use Base64 to encode the image:
public void sendImage(String path)
{
JSONObject sendData = new JSONObject();
try{
sendData.put("image", encodeImage(path));
socket.emit("message",sendData);
}catch(JSONException e){
}
}
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
So basically you are sending a string to node.js
If you want to receive the image just decode in Base64:
private Bitmap decodeImage(String data)
{
byte[] b = Base64.decode(data,Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(b,0,b.length);
return bmp;
}
I am trying to encode images using base64 encoding on the image URL.
But it gives the same encoding for all the URLs.
My code is as follows:
Object namee = url.openConnection().getContentType();
String name = (String) namee;
BufferedImage image = ImageIO.read(url);
//getting image extension from content type
String ext = name.substring(name.lastIndexOf("/") + 1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, ext, baos);
byte[] imageData = baos.toByteArray();
String base64value = Base64.encodeBase64URLSafeString(imageData);
This Code convert your image file/data to Base64 Format which is nothing but text representation of your Image.
To convert this you need Encoder & Decoder which you will get from http://www.source-code.biz/base64coder/java/. It is File Base64Coder.java you will need.
Now to access this class as per your requirement you will need class below:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Base64 {
public static void main(String args[]) throws IOException {
/*
* if (args.length != 2) {System.out.println(
* "Command line parameters: inputFileName outputFileName");
* System.exit(9); } encodeFile(args[0], args[1]);
*/
File sourceImage = new File("back3.png");
File sourceImage64 = new File("back3.txt");
File destImage = new File("back4.png");
encodeFile(sourceImage, sourceImage64);
decodeFile(sourceImage64, destImage);
}
private static void encodeFile(File inputFile, File outputFile) throws IOException {
BufferedInputStream in = null;
BufferedWriter out = null;
try {
in = new BufferedInputStream(new FileInputStream(inputFile));
out = new BufferedWriter(new FileWriter(outputFile));
encodeStream(in, out);
out.flush();
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}
private static void encodeStream(InputStream in, BufferedWriter out) throws IOException {
int lineLength = 72;
byte[] buf = new byte[lineLength / 4 * 3];
while (true) {
int len = in.read(buf);
if (len <= 0)
break;
out.write(Base64Coder.encode(buf, 0, len));
out.newLine();
}
}
static String encodeArray(byte[] in) throws IOException {
StringBuffer out = new StringBuffer();
out.append(Base64Coder.encode(in, 0, in.length));
return out.toString();
}
static byte[] decodeArray(String in) throws IOException {
byte[] buf = Base64Coder.decodeLines(in);
return buf;
}
private static void decodeFile(File inputFile, File outputFile) throws IOException {
BufferedReader in = null;
BufferedOutputStream out = null;
try {
in = new BufferedReader(new FileReader(inputFile));
out = new BufferedOutputStream(new FileOutputStream(outputFile));
decodeStream(in, out);
out.flush();
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}
private static void decodeStream(BufferedReader in, OutputStream out) throws IOException {
while (true) {
String s = in.readLine();
if (s == null)
break;
byte[] buf = Base64Coder.decodeLines(s);
out.write(buf);
}
}
}
In Android you can convert your Bitmap to Base64 for Uploading to Server/Web Service.
Bitmap bmImage = //Data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageData = baos.toByteArray();
String encodedImage = Base64.encodeArray(imageData);
This “encodedImage” is text representation of your Image. You can use this for either uploading purpose or for diplaying directly into HTML Page as below:
<img alt="" src="data:image/png;base64,<?php echo $encodedImage; ?>" width="100px" />
<img alt="" src="data:image/png;base64,/9j/4AAQ...........1f/9k=" width="100px" />
Here is a working example on how to convert image to base64 with Java.
public static String encodeToString(BufferedImage image, String type) {
String base64String = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
base64String = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return base64String;
}