To display a Base64 image in AngularJS - java

I have inserted a Base64 image to a database using this Java code:
FileInputStream mFileInputStream = new FileInputStream("C:\\basicsworkspace\\base64upload\\src\\main\\resources\\basic.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ((bytesRead = mFileInputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] ba = bos.toByteArray();
//byte[] encoded = Base64.getEncoder().encode(ba); // Util
byte[] encoded = Base64.encodeBase64(ba); // Apache
connection = DriverManager.getConnection(connectionString);
String insertSql = "INSERT INTO test (image) VALUES (?)" ;
prepsInsertProduct.setBytes(encoded);
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
System.out.println(prepsInsertProduct.execute());
But if I try to display the image in AngularJS using it, it is not displaying the image. In SQL Server I have saved my image as varbinary(max) and in AngularJS code,
config(function ($compileProvider) {
console.log($compileProvider.imgSrcSanitizationWhitelist());
})
<img src="choice:image/png;base64,{{choice.Icon}}">
But I am getting only bytes with a message like this:
unsafe:choice:image/png;base64,6956424F5277304B47676F414141414E535568455567…
Where am I going wrong? The image is in PNG format.

In POJO I made changes for byte[] and it worked. I have datatype with String and modified to byte[] but Base64 images didn't displayed but t is displaying only byte array images.

Try in your controller:
$scope.choice.Icon = 'data:image/jpeg;base64,' + yourImageData;
And in your HTML content:
<img ng-src="{{choice.Icon}}">

Related

Convert ByteArray to Base64 [duplicate]

This question already has answers here:
How do I convert a byte array to Base64 in Java?
(4 answers)
Closed 1 year ago.
How can I convert an image like this one into a Base64 string?
I upload the image to the server with React, scale it, save it in the database, read it out again and get this format.
Now I have to convert this format into a Base64 format.
My Java Code to scale the image:
Part bild = request.getPart("bild");
InputStream in = null;
long fileSize = bild.getSize();
byte[] bytesBild = null;
if (fileSize > 0) {
in = bild.getInputStream();
BufferedImage imBuff = ImageIO.read(bild.getInputStream());
BufferedImage resize = resizeImage(imBuff, 200, 200);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(resize, "jpeg", os); // Passing: ​(RenderedImage im, String formatName, OutputStream
// output)
InputStream is = new ByteArrayInputStream(os.toByteArray());
bytesBild = IOUtils.toByteArray(is);
}
This is the result from my Database:
You could use the native java.util.Base64 class.
Save to database
//...
bytesBild = IOUtils.toByteArray(is);
String imgEncodedString = Base64.getEncoder().encodeToString(bytesBild);
//imgEncodedString --> ddbb
Read from database
byte[] imgDecodedBytes = Base64.getDecoder().decode(imgEncodedString);
ByteArrayInputStream bis = new ByteArrayInputStream(imgDecodedBytes);
//...

PNG image from java server to android

I'm trying to send multiple PNG:s to an adroid-phone.
(Every image is sent in a separate JSON-object together with multiple other objects that is associated with the image.)
I'm sending the images as byte-arrays and my phone is receiving them.
The problem starts when I try to decode with BitmapFactory.decodeByteArray which returns null.
How should I encode on the server-side and decode on the android-side?
First attempt on server-side:
File imgPath = new File(path);
BufferedImage bufferedImage = ImageIO.read(imgPath);
WritableRaster raster = bufferedImage.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] bytes = data.getData();
Second attempt on server-side:
byte[] bytes = null;
File file = new File(path);
bytes = Files.readAllBytes(file.toPath());
Android-side:
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mImageView.setImageBitmap(bitmap);
Sending JSON from server:
public class Response {
List<Person> mPeople;
..other objects...
}
public class Person {
String name;
String image; //base68string
}
public ServerThread {
Response resp = create objects to send;
String str = new Gson().toJson(resp);
OutputStreamWriter.write(str);
}
Receiving JSON on Android-side:
Response resp = gson.fromJson(str, Response.class);
List<Person> = resp.getPersons();
//Person-class on the android side is Parcable
So I tried this approach but it still doesn't work:
// Server-side
import java.util.Base64;
import java.util.Base64.Encoder;
File file = new File(path);
byte[] bytes = Files.readAllBytes(file.toPath());
Encoder e = Base64.getEncoder();
String base64String = e.encodeToString(bytes);
//Android-side
byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
mImageView.setImageBitmap(bitmap);
I suggest you to try Picasso or Glide to load image into imageview directly from the URL. You don't have to manage this all stuff manually.
I was doing that stuff but after using one of this library it removes lots of work.
Just try this.

Trying to insert Base64 image to sql server database

//Convert binary image file to byte array to base64 encoded string
FileInputStream mFileInputStream = new FileInputStream("C:\\basicsworkspace\\base64upload\\src\\main\\resources\\basic.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ((bytesRead = mFileInputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] ba = bos.toByteArray();
byte[] encoded = Base64.getEncoder().encode(ba);
connection = DriverManager.getConnection(connectionString);
String insertSql = "INSERT INTO test (image) VALUES "
+ "("+encoded+")";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(
insertSql);
System.out.println(prepsInsertProduct.execute());
Trying to insert image to sql server and need to have the image as base64 format. I am getting below exception. Please let me know what type of datatype and how to insert image as base64 in sql server.
Output :
INSERT INTO test (image) VALUES ([B#7229724f)
java.sql.SQLException: Invalid SQL statement or JDBC escape, terminating ']' not found.
at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:1270)
at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:165)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.<init>(JtdsPreparedStatement.java:111)
at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2492)
at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2450)
at base64upload.base64upload.App.main(App.java:70)
You are just concatenating string with toString() value of byte array. That's incorrect. You should use another approach:
String insertSql = "INSERT INTO test (image) VALUES (?)";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
// here set your array
prepsInsertProduct.setBytes(encoded);

How to convert image into bit plane in android?

I have a project in an android platform that the process should force me to convert image into bit-plane, but I don't know how is the code.
The images are from gallery and taken from camera.
Please help.
try this:
String encoded = Base64.encodeFromFile("data/inputImage.png");
//Convert String data to binary image file
Base64.decodeToFile(encoded, "data/outputImage.png");
//Convert binary image file to byte array to base64 encoded string
FileInputStream mFileInputStream = new FileInputStream("data/inputImage.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ((bytesRead = mFileInputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] ba = bos.toByteArray();
encoded = Base64.encodeBytes(ba);
//Convert String data to binary image file
Base64.decodeToFile(encoded, "data/outputImage.png");
//Convert binary image file to base64 encoded String data file
Base64.encodeFileToFile("data/inputImage.png","data/encodedImage.txt");
//Convert base64 encoded String data file to binary image file
Base64.decodeFileToFile("data/encodedImage.txt","data/outputImage.png");
Source http://www.mysamplecode.com/2011/07/convert-image-to-string-and-string-to.html

HtmlUnit use WebClient to download an image as base64 encoded DATA Uri

I want to use an existing instance of WebClient to download an image. The reason for this is because I want the cookies to be passed with the request.
How can I download an image using an existing instance of WebClient?
Also, how can I base64 encode the image to be able to view it using data:image/jpeg;base64,...
Current code:
WebClient client = new WebClient(BrowserVersion.FIREFOX_3_6);
UnexpectedPage imagePage = client.getPage("http://...");
String imageString = imagePage.getWebResponse().getContentAsString();
BASE64Encoder encoder = new BASE64Encoder();
String base64data = encoder.encode(imageString.getBytes());
So now I have base64 data of the image, but I still can't view the image using data:image/jpeg;base64,....
A couple of things to consider:
The BASE64Encoder() generates a string that has a line break every 77 chars. Take that out using .replaceAll("\r?\n","").
For that method also, it is better to retrieve the web page InputStream rather than the string. Also, to convert that to a byte array, I used a utility method (source and other options can be found here).
Working source code:
public static void main (String args[]) throws IOException {
WebClient client = new WebClient(BrowserVersion.FIREFOX_3_6);
UnexpectedPage imagePage = client.getPage("http://i.stack.imgur.com/9DdHc.jpg");
BASE64Encoder encoder = new BASE64Encoder();
String base64data = encoder.encode(inputStreamToByteArray(imagePage.getWebResponse().getContentAsStream()));
System.out.println("<img src=\"data:image/png;base64,"+base64data.replaceAll("\r?\n","")+"\" />");
}
private static byte[] inputStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
Source image:
Output base64 image here.

Categories

Resources