how do i load image from resource inside TembeddedWB - html

iam trying to load image from resource inside image htmlTag as example
<img src="'+ Resourceimage +'">
i tried to do something like this
function getFullHTML(res:string):string;
var
sURL : string;
resorceimg : TResourceStream;
begin
resorceimg := TResourceStream.Create(HInstance, res, RT_RCDATA);
sURL := 'res://'+ resorceimg +'';
end;
then i call the function like this
<img src="'+ getFullHTML('imagename') +'">
but i cannot use a TResourceStream into string i think iam doing it in horrible way how exactly i can load image from resource into html image ?

You can use Data URIs with Base64 encoded images:
Embedding Base64 Images
The image is then embedded like
<img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
The anwers to the linked question list supported browsers.

Related

How to display livestream image in HTML? Trying to convert bytes to base64 and display in <img> element (using electron and vue)

In my electron/vue app i recieve images as Bytes from a python backend.
I collect all the bytes and trying to convert it to base64
let buff = new Buffer(imageBytes);
let base64data = buff.toString('base64');
this.emitter.emit('livestream', base64data);
in my viewrenderer I set the livestream vue data
ipcRenderer.on('livestream', (event, data: any) => {
app.livestream = `data:image/bmp;base64,${data}`;
});
and I bind it to the img tag in the HTML
<img v-bind:src="livestream" class="livestreamElement" id="livestreamElement">
But it doesn't work, I get no image to the tag to be displayed at all.
Any suggestions? Am I doing something wrong or is there any better solution for this?

How can I display image by href tag pointing to REST api?

I'm building some web app. On my frontend side I need to display images which are earlier uploaded to spring-boot hsqldb. Image data is stored as a BLOB type in database. I want to display them as:
<img href="/api/photos/0">
In the past I was sending GET request to my api to get image data as byte array, than encoding it to Base64, sending back as a string "data:image/jpg;base64, myData" and putting it to img src and it worked perfectly.
Now I want to check some different approach and I got stuck.
This is my vue template:
<div class="card">
<div class="card-header"><h4>Some header</h4></div>
<div class="card-body">
<img class="card-img-top" :href="url">
</div>
</div>
This is my vue method building url:
export default {
data(){
return{
url:''
}
},
mounted() {
this.makeUrl();
},
methods:{
makeUrl(){
this.url="/api/photos/0";
}
}
}
And this is my spring-boot api controller:
#GetMapping(value = "/photos/{id}")
public String readPhoto(#PathVariable Long id){
return makePhotoUrl(photosRepository.findById(id).get().getData());
}
private String makePhotoUrl(byte[] photo){
String photoUrl = "data:image/jpeg;base64," +
Base64.getEncoder().encodeToString(photo);
return photoUrl;
}
I do get image data by accessing url directly by a browser, but my card is still empty.
Please help because i have no more ideas how to make it work.
So, after another day of research I've finally figured it out. Basically I've made two mistakes.
First, href specifies link destination, but it should be used only with "a" tag:
link
If i want to specify img source I should use "src":
<img src = "www.someOtherWebsite.com">
Second, it appears that if I want to return url as a direct response from api, it must point to a physical file. I might be wrong, so please correct me.
I've changed my controller to:
public ResponseEntity<Resource> readPhotoById(Long id) {
Photo photo = photosRepository.findById(id).get();
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(photo.getType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + photo.getName() + "\"")
.body(new ByteArrayResource(photo.getData()));
}
Now it works as expected.
Cheers :)

Regex capture string between delimiters and excluding them

I saw in this forum an answare close to my "request" but not enough
(Regexp to capture string between delimiters).
My question is: I have an HTML page and I would get only the src of all "img" tags of this page and put them in one array without using cheerio (I'm using node js).
The problem is that i would prefer to exclude the delimiters.
How could i resolve this problem?
Yes this is possible with regex, but it would be much easier (and probably faster but don't quote me on that) to use a native DOM method. Let's start with the regex approach. We can use a capture group to easily parse the src of an img tag:
var html = `test<div>hello</div>
<img src="first">
<img class="test" src="second" data-lang="en">
test
<img src="third" >`;
var srcs = [];
html.replace(/<img[^<>]*src=['"](.*?)['"][^<>]*>/gm, (m, $1) => { srcs.push($1) })
console.log(srcs);
However, the better way would be to use getElementsByTagName:
(note the following will get some kind of parent domain url since the srcs are relative/fake but you get the idea)
var srcs = [].slice.call(document.getElementsByTagName('img')).map(img => img.src);
console.log(srcs);
test<div>hello</div>
<img src="first">
<img class="test" src="second" data-lang="en">
test
<img src="third" >

Displaying images in webpage without src URL

Recently i learned that i can display images in a web page without referencing an image URL as follows :
<img class="disclosure" img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oIGRQbOY8MjgMAAABVSURBVBjTfc6xDcAwCETRM0rt5nbA+49j70DDAqSLsGXyJQqkVxxwNOeMiEA+waW1VuT/inrvG7wikht8UETy2ygVMjO4O8YYTf6AqrZyUwYlygAAXo+QLmeF4c4uAAAAAElFTkSuQmCC">
I had another small bmp image that i wanted to display, so i opened it in vim and the img source looke like:
When i paste this code where it needs to be pasted i only get "BMڀ"
How to i convert/paste this code properly to be used as an image source?
You need to encode it in Base64
http://www.motobit.com/util/base64-decoder-encoder.asp
Also you have to change (png) in...
<img src="data:image/png;base64,
according to image filetype.
Here is a little PHP function, haven't tested it.
function encode64($file){
$extension = explode(".", $file);
$extension = end($extension);
$binary = fread(fopen($file, "r"), filesize($file));
return '<img src="data:image/'.$extension.';base64,'.base64_encode($binary).'"/>';
}
echo encode64("test.bmp");
2.
function encode64($file){
$binary = fread(fopen($file, "r"), filesize($file));
return(base64_encode($binary));
}
echo '<img src="data:image/bmp;base64,'.encode64("test.bmp").'"/>';
Tested my second function... works great... http://debconf11.com/so.php
You can use online utilities like
http://software.hixie.ch/utilities/cgi/data/data
or
http://www.sveinbjorn.org/dataurlmaker
for the conversion.
To get the Base64 encoding of your image, you can use imagemagick's convert command with the INLINE: output format.
For example:
convert YourImage.png INLINE:PNG:YourImage_base64.txt
Now all you have to do in your HTML page is add <img src=" and "> around the content of the "YourImage_base64.txt" file.
Or you can directly write it all to STDOUT and add it directly at the end of your HTML file:
echo "<img src=\"$(convert YourImage.png INLINE:PNG:-)\">" >> some.html
The image data must be base64 encoded.

Grails: displaying created image in gsp

I'm very new to Grails so there's probably a very simple answer to this question. I'm trying to display a dynamically created image in a gsp. The image is NOT stored in a database, it's created on the fly in the controller.
What I essentially have is one gsp that has a form which takes in a set of user inputs (requestGraph.gsp). Upon submitting the form, the parameters are sent to the a displayGraph action in the controller which queries information from a database completely outside of Grails and creates a chart using the JFreeChart library. I would like to display this image within a displayGraph.gsp or something like that.
So basically within requestGraph.gsp I have a snippet similar to:
<g:form action="displayGraph">
<!-- ... bunch of labels and boxes -->
<g:submitButton name="displayGraph" value="Display Graph" />
</g:form>
Within the controller I have something like:
def requestGraph = {}
def displayGraph = {
//... code that uses params to make an image byte array and assigns to var img
return [image : img]
}
Within displayGraph.gsp:
<body>
<h1>Graph Title</h1>
<!-- ??? How to dislpay image? -->
</body>
I tried piping the image directly to the output stream in the displayGraph action. This works, but then I lose control of all page formatting in displayGraph.gsp.
Most tutorials I've found create a dedicated action to pipe the image to an output steam then call that action using a tag. The problem is that my image isn't stored in a database and I see no way of passing the image byte array (or even the form parameters) to create/render the image. Can anybody help me with this? Thanks.
If you write the bytes to the output stream, you can treat the controller/action as the source of the image in your GSP. Here's a quick, untested example:
// controller action
def displayGraph = {
def img // byte array
//...
response.setHeader('Content-length', img.length)
response.contentType = 'image/png' // or the appropriate image content type
response.outputStream << img
response.outputStream.flush()
}
You could then access your image in the src of an <img> tag like this:
<img src="${createLink(controller: 'myController', action: 'displayGraph')}"/>
Update:
After reading your question again, this may or may not work - it looks like you might be displaying the graph as the result of a form submission. This will only work if you're storing the state on the server somewhere (instead of just getting it from the one request where the form is submitted). If you do store enough state on the server to generate the graph, then you'd have to provide some additional parameters to your controller to get the correct image, e.g. src="${g.link(controller: 'myController', action: 'displayGraph', params: ['id': 1234])}", where id is how you retrieve the graph state.
The following code works in Grails 2.x.
HomeController.groovy
class HomeController {
def index() {
}
def viewImage(){
def file = new File(params.title)
def img = file.bytes
response.contentType = 'image/png' // or the appropriate image content type
response.outputStream << img
response.outputStream.flush()
}
}
views/home/index.jsp
<%# page contentType="text/html;charset=ISO-8859-1" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<meta name="layout" content="main"/>
<title>View Image</title>
</head>
<body>
<div class="body">
<img src="<g:createLink controller="home" action="viewImage"
params="[title: 'C:/pictures/myimage.png']"/>"/>
</div>
</body>
</html>
I believe it's not about Grails but about HTML. You could:
Make the dedicated action that pipes image accept certain parameters, and generate the image in that action;
Embed it base64-encoded into HTML, like here:
<img src="data:image/gif;base64,R0lGODlhUAAPAKIAAAsL...etc..." alt="wow" />
my suggestion actually has two parts.
1) Use the solution recommend by Rob above to generate the chart artifact, however save it to a static file with a unique identifier that is passed back as part of the response from the form submit, then rendering the chart is no different then rendering any other image.
i would suggest that the identifer be constructed from the specifif params passed in on the form submit so they can be used as a caching mechanism to render the chart again without rebuilding it
2) create a service, maybe a Quartz Service, that periodically cleans up the static charts that were created for the application
Just an improvement to #Rob's answer:
Another option which is a bit nicer, you can just render the image, straight from your controller's action:
// controller action
def displayGraph = {
def img // a byte[], File or InputStream
render(file: img, contentType: 'image/png')
}
See also: http://grails.org/doc/latest/ref/Controllers/render.html
For any reasons the above solutions does not display any image. I used:
<img src='${createLink(controller: "myController", action: "displayGraph")}' />
instead.
I used FileUploadService to save the Image file In Grails .If you getting images from directory means, try this:
<img style="height: 120px;width: 102px;"src="${resource(dir:'personImages', file: personalDetailsInstance.id + '.png')}" />
Your gsp:
<img src="${createLink(controller: "image", action: "draw")}" />
Your controller:
def draw() {
byte[] imageInBytes = imageService.getImageInBytes() //should return byte array
response.with{
setHeader('Content-length', imageInBytes.length.toString())
contentType = 'image/jpg' // or the appropriate image content type
outputStream << imageInBytes
outputStream.flush()
}
}