Base64 image encoding using java - java

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

Related

convert pdf to byteArray - byteArray to String - String to byteArray - byteArray to pdf

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

How to get PDF file from web using java streams

I need to download PDF file from web, for example http://www.math.uni-goettingen.de/zirkel/loesungen/blatt15/loes15.pdf this link. I have to do it using Streams. With images it works fine by me :
public static void main(String[] args) {
try {
//get the url page from the arguments array
String arg = args[0];
URL url = new URL("https://cs7065.vk.me/c637923/v637923205/25608/AD8WhOSx1ic.jpg");
try{
//jpg
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[131072];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("borrowed_image.jpg");
fos.write(response);
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
But with PDf it does not work. What could be the problem ?
I made minor edits to your code to fix syntax errors and, this seems to work (below). Consider placing your close() statements in a finally block.
package org.snb;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class PdfTester {
public static void main(String[] args) {
//get the url page from the arguments array
try{
//String arg = args[0];
URL url = new URL("http://www.pdf995.com/samples/pdf.pdf");
//jpg
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[131072];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("/tmp/bart.pdf");
fos.write(response);
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
try this, this got the job done (and pdf is readable).
see if there are any exceptions thrown when requesting the url.
public static void main(String[] args) {
try {
//get the url page from the arguments array
URL url = new URL("http://www.math.uni-goettingen.de/zirkel/loesungen/blatt15/loes15.pdf");
try {
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[131072];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("loes15.pdf");
fos.write(response);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}

How do I convert a big hexadecimal file to a binary file?

I Have a text file with the size of 2.4MB
How can I convert it into java?
I use this code but it is not valid:
This initializes the File:
File file = new File("E:/Binary.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try {
String sCurrentLine;
String bits ="";
br = new BufferedReader(new FileReader("E:/base1.txt"));
while ((sCurrentLine = br.readLine()) != null) {
bits = hexToBin(sCurrentLine);
}
bw.write(bits);
bw.close();
System.out.println("done....");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
This Methods to convert:
static String hexToBin(String s) {
return new BigInteger(s, 16).toString(2);
}
I don't understand what do you mean by a hex file, any file can be read as a binary one and here is an example on how to read & write a binary file:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class BinaryFiles {
public static void main(String... aArgs) throws IOException{
BinaryFiles binary = new BinaryFiles();
byte[] bytes = binary.readBinaryFile(FILE_NAME);
log("size of file read in:" + bytes.length);
binary.writeBinaryFile(bytes, OUTPUT_FILE_NAME);
}
final static String FILE_NAME = "***srcPath***";
final static String OUTPUT_FILE_NAME = "***destPath***";
byte[] readBinaryFile(String aFileName) throws IOException {
Path path = Paths.get(aFileName);
return Files.readAllBytes(path);
}
void writeBinaryFile(byte[] aBytes, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aBytes); //creates, overwrites
}
private static void log(Object aMsg){
System.out.println(String.valueOf(aMsg));
}
}
If you want to convert hex to binary use this:
String hexToBinary(String hex) {
int intVal = Integer.parseInt(hex, 16);
String binaryVal = Integer.toBinaryString(intVal);
return binaryVal;
}
You could use the above example to make a combination of converting HEX to binary then writing it.

How to download WordPress with Java

I want to download WordPress with Java.
My code looks like this:
public void file(String surl, String pathToSave) throws IOException {
URL url = new URL(surl);
sun.net.www.protocol.http.HttpURLConnection con = (HttpURLConnection) url.openConnection();
try (InputStream stream = con.getInputStream()) {
Files.copy(stream, Paths.get(pathToSave));
}
}
I am using this url to download the latest version of WordPress: http://wordpress.org/latest.tar.gz
But when I try extracting the tar.gz file I get an error saying the file is not in a gzip format.
I read this Issues uncompressing a tar.gz file and it looks like when I download WordPress I need to have a cookie enabled to accept the terms and services.
How would I do this?
Or am I incorrectly downloading the tar.gz file?
Here is what my tar.gz extracting code:
public class Unzip {
public static int BUFFER = 2048;
public void tar(String pathToTar, String outputPath) throws IOException {
File tarFile = new File(pathToTar);
TarArchiveInputStream tarInput =
new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(tarFile)));
TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
while(currentEntry != null) {
if (currentEntry.isDirectory()) {
File f = new File(outputPath + currentEntry.getName());
f.mkdirs();
}
else {
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(outputPath
+ currentEntry.getName());
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
while ((count = tarInput.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.close();
}
}
}
}
Thanks in advance.
Change sun.net.www.protocol.http.HttpURLConnection to java.net.HttpURLConnection
Add fos.close() after dest.close()
You must call currentEntry = tarInput.getNextTarEntry(); inside the while loop, too.
There is nothing with cookie enabled or accept the terms and services.
Here is my complete code.
Please try this and compare it to your code:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
public class Downloader {
public static final int BUFFER = 2048;
private void download(String surl, String pathToSave) throws IOException {
URL url = new URL(surl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try (InputStream stream = con.getInputStream()) {
Files.copy(stream, Paths.get(pathToSave));
}
}
private void unGz(String pathToGz, String outputPath) throws IOException {
FileInputStream fin = new FileInputStream(pathToGz);
BufferedInputStream in = new BufferedInputStream(fin);
try (FileOutputStream out = new FileOutputStream(outputPath)) {
try (GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in)) {
final byte[] buffer = new byte[BUFFER];
int n = 0;
while (-1 != (n = gzIn.read(buffer))) {
out.write(buffer, 0, n);
}
}
}
}
public void unTarGz(String pathToTar, String outputPath) throws IOException {
File tarFile = new File(pathToTar);
TarArchiveInputStream tarInput
= new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(tarFile)));
TarArchiveEntry currentEntry;
while ((currentEntry = tarInput.getNextTarEntry()) != null) {
if (currentEntry.isDirectory()) {
File f = new File(outputPath + currentEntry.getName());
f.mkdirs();
} else {
int count;
byte data[] = new byte[BUFFER];
try (FileOutputStream fos = new FileOutputStream(outputPath
+ currentEntry.getName())) {
try (BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER)) {
while ((count = tarInput.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
}
}
}
}
}
public static void main(String[] args) throws IOException {
Downloader down = new Downloader();
down.download("https://wordpress.org/latest.tar.gz", "/tmp/latest.tar.gz");
down.unTarGz("/tmp/latest.tar.gz", "/tmp/untar/");
}
}

Receiving Image file in java

I am using basic java Server Client module to send a picture.
I am using this link for guidance
Below is my source code for the client.I have issues while receiving the file.
package sclient;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class Sclient {
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("192.168.0.10", 123);
byte[] mybytearray = new byte[1024*1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir")+"/imageTest.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
Thats one util method of an android project, but its does the same. Reads and write is somewhere
/**
* #param inputStream
* #param inClose
* #return
* #throws IOException
*/
public static byte[] readContent(#NonNull final InputStream inputStream, final boolean inClose)
throws IOException {
Preconditions.checkNotNull(inClose, "InputStream");
//
final ByteArrayOutputStream theStream = new ByteArrayOutputStream(BUFFER_2K);
final byte[] theBuffer = new byte[BUFFER_2K];
try {
int theLength = inputStream.read(theBuffer);
while (theLength >= 0) {
theStream.write(theBuffer, 0, theLength);
theLength = inputStream.read(theBuffer);
}
return theStream.toByteArray();
} finally {
if (inClose) {
close(theStream);
}
}
}

Categories