how to display byte[] as picture in html with java - javascript

I use spring mvc and JPA in my project. I get file as byte[] and save in Database. but when I want to display in <img tag of html it don't display.
my entity is:
class Photo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
#Lob
private byte[] profilePic;
// getter and setter
}
value in Database is:
but my server response is:
{
"id": 4,
"title": "pic 1",
"profilePic": "ZGF0YTppb...VFtQ0M=",
}
and display in html:
<img src='ZGF0YTppb...VFtQ0M=' />
//or
<img src='data:image/jpeg;base64,ZGF0YTppb...VFtQ0M=' />
What to do to display the photo?
thanks

Assuming it's base64 encoded:
<img src='data:image/jpeg;base64,ZGF0YTppb...VFtQ0M=' />
Basically you can use data urls with this format depending on what content [type] you want to display:
data:[<mime type>][;charset=<charset>][;base64],<encoded data>

HTML:
<img id="profileImg" src="">
JS:
document.getElementById("profileImg").src = "data:image/png;base64," + profilePic;
This assumes that your image is stored in PNG format (and base64 encoded). For other image format (JPEG, etc.), you need to change the MIME type ("image/..." part) in the URL.

Related

How to show a base64 image in html

I get some information from the API that has a property called pic (image) which is base64
like this:
{description: "description"
id: 1
isActive: false
max: 10
min: 1
pic: "W29iamVjdCBGaWxlXQ==" //-->is base64
rewardCategoryEnTitle: "test"
rewardCategoryId: 2
rewardCategoryTitle: "test"
scoreValue: 200
title: "test"}
How can I show it in tag <img/>?
all you have to do is include data:image/jpg;base64, infront of the base64 string. You can change jpg to whatever file type you want it to be
<img src="data:image/jpg;base64,....."/>
so if you are using react it would probably be like this
<img src={`data:image/jpg;base64,${objectName.pic}`}/>
If it is valid base64 you can show it like this
<img class="itemImage" src="{{ 'data:image/png;base64,' + photo }}"/>
Validate your base64 string here.

Set a value of file input in Angular 8 when editing an item

I have an angular 8 program where I want to edit an item upon clicking edit and the value shows up in their respective forms. So for the name value will display in the name text input. Age will display in the age text input, etc. The problem is when I click edit, the image input file doesn't display or hold the image.
Now how do I display this image by default when clicking edit similar to the text files? I know the text inputs use [(ngModel)] = "value"/>but this doesn't seem to work for input files. Below is my code for the image input file and the corresponding ts file.
HTML
<div class="form-group">
<input formControlName="ProductFile" #file type="file" name="photo" ng2FileSelect [uploader]="uploader" (change)="previewImage(file.files)" />
<div [hidden]="!imgURL">
<img [src]="imgURL || '//:0'" height="200" >
</div>
</div>
edit file.ts
previewImage(files, product) {
if (files.length === 0)
return;
var mimeType = files[0].type;
if (mimeType.match(/image\/*/) == null) {
return alert('Only image files!');
}
var reader = new FileReader();
this.imagePath = files;
reader.readAsDataURL(files[0]);
reader.onload = (_event) => {
//upload percentage
this.uploadPercent = new Observable((observer) => {
Math.round((_event.loaded / _event.total) * 100);
});
this.imgURL = reader.result;
}
}
Need Clarification
Your previewImage function is receiving two arguments but you seem to be sending only one.
Do you want to show a default image before the user selects a file? If this is the case, the change() lifehook will not help. That is only fired after a new file is selected.
Possible solution
You can save a default file in your assets folder, or anywhere in your filesystem really, and pass it as a default value for imageURL:
imageUrl = 'default-path/file.ext'
If you are getting the default file from a server, send it as a member of a dto class, with byte[] as its datatype. You can then pass in the raw bytes into src:
// model.kt
data class FileDto(content: ByteArray, ext: string)
// controller
#GetMapping(value = ["/file/{fileId}"])
fun getFile(#PathVariable("fileId") fileId: string): FileDto {
return fileService.fetchFile(UUID.fromString(fileId))
}
// file-service.kt
// assuming filePath and ext are columns in your db table
fun fetchFile(fileId: UUID): FileDto {
return try {
db.findById(fileId).let {
FileDto(FileSystemResource(it.filePath).file.readBytes(), it.ext)
}
}
catch (e: FileNotFoundException) { handleExceptions(e) }
catch(e: IOException) { handleExceptions(e) }
}
private fun handleExceptions(e: Exception): Nothing {
e.printStackTrace()
throw e
}
This endpoint will give you everything you need to display the file:
client-side
// model.ts
// note that the byte array will be stringified (serialized)
// since it is coming from a data class
export interface File {ext: string, content: string}
// file-service.ts
fetchFile(uuid: string): Observable<File> {
return this.httpClient.get<File>(this.baseUrl + 'uuid')
}
//app.component.ts
mimeTypes = new Map([
['jpeg', 'image/jpeg'],
['svg', 'image/svg+xml'],
['pdf', 'application/pdf'],
['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
])
imageUrl$ = this.fileService.fetchFile(uuid).pipe(
map(it => this.generateFileUri(it.ext, it.content))
)
private generateFileUri(ext: string, content: string) {
const mimeType = MimeTypes.get(ext)
return `data:${mimeType};base64,${content}`
}
//app.component.html
<img [src]="(imgUrl$ | async) || '//:0'" height="200" >
Now how do I display this image by default when clicking edit similar to the text files? [...] this doesn't seem to work for input files.
I tried to reproduce your issue in a StackBlitz project (see link).
Without modifying your sample code too much, here's how I got the image to display from input file:
From your template, supply a [formGroup] directive in the root div HTML element.
<div class="form-group" [formGroup]="form">
...
</div>
In your component class, define the supplied form form group, which contains the ProductFile form control.
form = new FormGroup({
ProductFile: new FormControl(''),
});
Hope this helps.

Not able to load image

I am trying to keep the image path value in a variable and pass it to img src property, but its not working.
Below is my code...
<div class="js-container-assortmentlist">
#{
string layoutImage1 = "FORMULE1UNTIL3_MOBIELETAFEL1_A_SIDE.jpg";
string layoutImage2 = "FORMULE1UNTIL3_MOBIELETAFEL1_B_SIDE.jpg";
string imageSource1 = "~/images/TafelLayouts/" + layoutImage1;
string imageSource2 = "~/images/TafelLayouts/" + layoutImage2;
}
<div style="width:30%; margin-left: auto;margin-right: auto;display:block " id="layoutImage1">
<img class="" id="imgLayout" src="#imageSource1" alt="#layoutImage1">
</div>
<div style="width:30%; margin-left: auto;margin-right: auto;display:none " id="layoutImage2">
<img class="" id="imgLayout" src="#imageSource2" alt="#layoutImage2">
</div>
<br />
</div>
When I am providing the value for img src directly like "~/images/TafelLayouts/FORMULE1UNTIL3_MOBIELETAFEL1_A_SIDE.jpg" itsworking fine.
As i need to load dynamic images , so I need to pass this value dynamically.
You need to use Url.Content to correct translate ~/
#{
string layoutImage1 = "FORMULE1UNTIL3_MOBIELETAFEL1_A_SIDE.jpg";
string layoutImage2 = "FORMULE1UNTIL3_MOBIELETAFEL1_B_SIDE.jpg";
string imageSource1 = Url.Content("~/images/TafelLayouts/" + layoutImage1);
string imageSource2 = Url.Content("~/images/TafelLayouts/" + layoutImage2);
}
To get url dynamically you may create a custom UrlHelper on your project
namespace project.MyCustomExtensions
public static class UrlHelperExtensions
{
public static string ImageUrl(this UrlHelper url, string param1, string param2)
{
// your logic goes here
}
}
An them call it like this
#using project.MyCustomExtensions // using on top of your view
// your html code
<img class="" id="imgLayout" src="#Url.ImageUrl("someParamValue", "otherParamValue")" alt="#layoutImage2">

backbone and javascript: upload and store the image data in GAE datastore?

I have been searching through wherever possible but got no help at all for this question.
I am working on a small program using python GAE with backbone javascript, I want the user can create a new book with a html form given below and store the new book in the GAE datastore, the form contains strings and an image.
<form>
<div><label>Title:</label> <input type="text" id="title" name="book_title" ></div>
<div><label>Author:</label> <input type="text" id="author" name="book_author" ></div>
<div><label>Picture:</label> <input id="image" type="file" class="upload" name="img" /></div>
<div><img id="img_preview" src="#" alt="image" ></img></div>
<div><button class="create_book">Create Book</button></div>
</form>
selecting a book picture from the local file system is handled by displayPicture method in order to load a thumbnail image on the page for preview.
clicking "Create Book" button event is handled by the createBook method in javascript file:
event:{
"click .create_book": "createBook" ,
"change .upload": "displayPicture",
......
},
createBook:function(){
this.model.set({
title: $('#title').val(),
author: $('#author').val(),
image: this.pictureFile.name
});
......
app.bookList.create(this.model,{wait:true,
success:function(){
alert("A new book has been created!");
}
});
return false;
},
......
displayPicture: function(evt){
var files = evt.target.files;
if(files){
this.pictureFile = files[0];
var reader = new FileReader();
reader.onloadend = function(){
$('#img_preview').attr('src',reader.result).width(200).height(200);
};
reader.readAsDataURL(this.pictureFile);
},
..........
at the python server end:
class Book(db.Model):
title = db.StringProperty()
author = db.StringProperty()
image = db.BlobProperty()
class createBook(webapp.RequestHandler):
def post(self):
book = Book()
book.title = self.request.get("title")
book.author = self.request.get("author")
book.image = db.Blob(self.request.get("image"))
book.put()
......
application = webapp.WSGIApplication(
[
.....
('/books/?',createBook)
],
debug=Ture
)
I can only display the thumbnail picture on the page for preview, but fail to create the new book, the line "app.bookList.create(...)" does send a POST request to the python server end, and the request is handled by the "createBook" method, but Firebug shows the "self.request.get("title"/"author"/"image")" lines are just an empty string, which means the content of the form is not retrieved from the Http request properly.
can you tell what are the problems in my code snippet ? thanks for your help.
I think that your problem is likely that you are passing a model in to create. From the Backbone docs:
create collection.create(attributes, [options])
Convenience to create a new instance of a model within a collection.
create isn't expecting a model, because it creates a model; what it's expecting is a raw JSON object (eg. {foo: bar}).
*EDIT* Actually, that's incorrect, create can accept an (un-saved) model; leaving the next few lines here any way so this doesn't get too confusing.
You could fix this by doing:
app.bookList.create(this.model.attributes, {wait:true,
or:
app.bookList.create(this.model.toJSON(), {wait:true,
but really you don't need to use create at all because you don't need to create a model (you already have one). What you (probably) want to do is add the model you have to the collection:
app.bookList.add(this.model)
and then sync it with the server separately:
this.model.save(null, {wait:true,
success:function(){
alert("A new book has been created!");
}
});
In the python side, you should get the data from
self.request.body
Not
self.request.get('xxx')

Displaying images, which are stored in a string, on a JSP

I am using the below mentioned code on my JSP:
<%
List eCCategoryList = form.getCategoryList();
//Map<String, String> catNameImgMap = (Map<String, String>) session.getAttribute("catNameImgMap");
Map catNameImgMap = (Map) form.getBlogIdNameMap();
String strImage = "";
Iterator it = eCCategoryList.iterator();
ECircularCategory category = null;
int counter = 0;
while (it.hasNext()) {
category = (ECircularCategory) it.next();
strImage = (String) catNameImgMap.get(category.getName());
%>
strImage contains image which I need to display on my JSP. I tried displaying the images like:
<img src="<%=strImage%>" alt="Test Image 1" width="270" height="190"/>
but the above code is not working a simple blank space is shown and nothing else, I need to display the images on my JSP page each of which are stored in the strImage string, how do I do it?
Please suggest.
You could use JSTL tag:
<img src="<c:url value="<%=strImage%>"/> alt="Test Image 1" width="270" height="190"/>
Here is a good link about JSTL.
Hope it helps...

Categories

Resources