How to Get Image From <img src=""> Tag? - html

When I want to render a picture, I send a request to the server with the associated picture to render. What's odd is how it's returned:
<img src="https://blargh.com/displayTemplate?templateid=template1">
Where that link is supposed to be the image data.
Using this, how can I transform that into an image that I can display to the user? This is for a facebook app, I can't just embed the HTML. It needs to be displayed inside my AS App as a Bitmap or Sprite or anything, really. Trying to convert it to a Bitmap or BitmapData have failed...
The only other information I can give is that my templateLoader is a Loaderand its .data is supposed to carry the HTML.

Something like this:
var data:String = '<img src="https://blargh.com/displayTemplate?templateid=template1">';
// grab the src attribute
var url:Array = data.match(/<img src=\"(.*?)\">/);
if (url.length > 1){
var loader:Loader = new Loader();
loader.load(new URLRequest(url[1]));
addChild(loader);
}

Use e4x. I'm not sure if you're getting a string or the result format on your service call is already XML, but if it's a string, you'd do something like this:
var imgXML:XML = XML(yourString);//yourString contains <img src="https://blargh.com/displayTemplate?templateid=template1">
link = imgXML.#src;
Then, look at the code Zevan posted for how to use a Loader if you're using just AS, or use it as the source for an Image control in Flex.

Looks like the server is providing you with a link that dynamically looks up the image based on the GET data you're passing to the server (the ?templateid=template1). Too bad you didn't paste in the real link so that this theory could be proven. Take the real link and copy out the http:// portion, enter it into your browser and if the image appears then this is indeed the case.
If this is true, then you want to extract the link from the tag. You could do this with a regular expression, like so:
/\?)"(.?)"(.*)/
If you ran that regex against the full tag like you've provided above, then capture group 2 will contain just the HTTP link. You can then use a Loader object to fetch the image so you're actually downloading and presenting the binary image data instead of embedding HTML.
If you're going to be using Regex in AS3, then you absolutely must have the RegExr tool by grantskinner.com: http://gskinner.com/RegExr/desktop/.
Also, to get the data from capture group 2 we do this:
var imageTag:String = '<img src="https://blargh.com/displayTemplate?templateid=template1">'
var myHttpRegex:Regex = /\<img(.*?)"(.*?)"(.*)/;
var result:Object;
result = myHttpRegex.exec(imageTag);
if(result != null) {
var imgUrl:String = result[1];
}
Code is untested, but the concept is there.

Related

How to interpolate a variable into an attribute?

I need to display the correct image based on the variable userAccount.image which is a String containing the name of an image (ie "profile1.png"). I can't seem to figure out the syntax for passing variables into attributes in pug.
I looked at the documentation for pug and I believe I replicated the nearest example to my case with no luck.
script.
var image = '#{userAccount.image}'
img(src="/images/" + image)
The console throws the following error
GET http://localhost:3000/images/ 404 (Not Found)
meaning the variable image is an empty string. However when I console.log(image) in the script it shows "profile1.png"
I figured out a way around it.
img(id="img")
script.
var imgTag = document.getElementById("img")
var image = '#{userAccount.image}'
imgTag.setAttribute('src', "/images/" + image)

pChart:render the image to browser and embed in html

I have a class name 'MonthReport.class.php' and its structure like the following:
class MonthReport{
.....
//some member variables
public function pieChart(){
........
//the image data comes from mysql and data belongs to a specified user
$myPicture->Stroke();
}
public function lineChart(){
........
//the image data comes from mysql and data belongs to a specified user
$myPicture->Stroke();
}
public function render html(){
$html.=str1<<<
.....
//some html code
str1;
$html.=<<<str2
<img src="$this->pieChart()" /> //can not work
str2;
}
}
when I call the pieChart() function with this in the place src it will overwrites my entire page and just shows the image.how can I do this?
I try to render the image in a separate page but the image need some specified user data eg.'userId'.in others words when i new a object, it specify the userId,so I can not render the image in a separate page.
sorry for my bad english!but I need your help!thanks in advancd!
Your question is a little unclear but if your problem is what I am assuming it to be, then I used to have similar issues (Graphic created that is just an image with all of the rest of my page content not displaying). My solution was to generate a temporary image using pchart then embed that file in the html
$myfilename = "temp_image.png"; // temp file name
$myPicture = new pImage(700,500,$myData);
// other image creation code....
$myPicture->Render($myfilename); // generate image "temp_image.png"
$image_html = '<img src="' . $myfilename . '">'; //generate the link
print("$htmlline");
Again there is some guesswork going on here as your question is unclear. The above works for me though and enables me to embed an image created on the fly by pChart into my php pages.

How to set ContextPath for an image link

i am trying to put context path for an image in HTML.<img src="/MyWeb/images/pageSetup.gif">
Here /MyWeb is the ContextPath which is hardcoded. How can i get dynamically.
i am using as <img src=contextPath+"/images/pageSetup.gif">but image is not displaying. Is there any option.
First of all, "Context path" is a term which is typically used in JSP/Servlet web applications, but you didn't mention anything about it. Your question history however confirms that you're using JSP/Servlet. In the future, you should be telling and tagging what server side language you're using, because "plain HTML" doesn't have a concept of "variables" and "dynamic generation" at all. It are server side languages like JSP which have the capability of maintaining and accessing variables and dyamically generating HTML. JavaScript can be used, but it has its limitations as it runs in webbrowser, not in webserver.
The question as you initially have will only confuse answerers and yield completly unexpected answers. With question tags you reach a specific target group. If you use alone the [html] tag, you will get answers which assume that you're using pure/plain HTML without any server side language.
Back to your question: you can use ${pageContext.request.contextPath} for this.
<img src="${pageContext.request.contextPath}/images/pageSetup.gif">
See also:
How to use relative paths without including the context root name?
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
You can't write JavaScript in the src attribute. To do what you want, try some code like this:
var img = new Image();
img.src = contextPath + "/images/pageSetup.gif";
document.getElementById('display').appendChild(img);
Here the target; the place where you want to display the image, is a div or span, with the id display.
Demo
With HTML, you'll have to take some extra traffic of producing an error, so you can replace the image, or you can send some traffic Google's way. Please do not use this:
<img src='notAnImage' onerror='this.src= contextPath + "/images/pageSetup.gif" '>
Demo
Do not use this.
You must use JavaScript for this.
First, have all images point to some dummy empty image on your domain while putting the real path as custom attribute:
<img src="empty.gif" real_src="/images/pageSetup.gif" />
Now have such JavaScript code in place to iterate over all the images and change their source to use the context path:
var contextPath = "/MyRealWeb";
window.onload = function() {
var images = document.getElementByTagName("img");
for (var i = 0; i < images.length; i++) {
var image = images[i];
var realSource = image.getAttribute("real_src") || "";
if (realSource.length > 0)
image.src = contextPath + realSource;
}
};

AS3 Not Adding Sprite to MovieClip

My code is simply looping through an xml file and creating 'pages' (which are later animated).
This has all worked fine but now I want to add a sprite over the entire contents of the page if the contents of the xml contain a URL.
At run-time I can see that the checks for the URL are being processed correctly and that the overlay is being generated, but I cannot "see" it on the page.
The following code is located in a for loop for every page in the xml file:
var page:Page = new Page(); //MovieClip in my library
// ... other stuff
var textMC:FadeText = new FadeText(xml); //load the text from the xml fragment for this page
//if the text contains a URL (using RegExp)
if(textMC.hasLink())
{
var button:Sprite = new Sprite();
button.graphics.beginFill(0x000000);
button.graphics.drawRect(0, 0, 1, 1);
button.name= textMC.getLink();
button.x = button.y = button.alpha = 0;
button.width = rectangle.width;
button.height = rectangle.height;
button.buttonMode = true;
button.addEventListener(MouseEvent.CLICK, goToUrl, false, 0, true);
page.addChildAt(button, page.numChildren);
}
//... more code - such as add page to stage.
From the console (using FireBug and FlashBug) the button is being created, but I cannot see it on screen so I am guessing the addChild bit is at fault.
What is wrong and how do I fix it?
[edit]
Having set the alpha to 1 I can see that the overlay IS being added to the page, but it is not changing my cursor or responding to mouse clicks.
I now believe it is something wrong with the XML. It is correctly parsed XML (otherwise FlashPlayer would throw exceptions in my face) and it appears that this code works on every page except the second. Further more, if the second page is set as visible (a flag in the XML determins if the page is created or not) then none of the other pages overlay works.
Sorry to necro this thread but one thing I can think of is that because you specify a z-position to place your page it might be that the z-position generated by (i+1) is not the next one in line. AS3 doesn't allow display-objects to be placed on 'layers' with empty 'layers' between them which was allowed in AS2.
My guess is that during the loop at one point or another the loop doesn't generate a page which leaves an empty layer. The reason why the stage.addChild(page) actually works is because it simply searches for the next empty layer in that stack because you don't specify it.
button.x = button.y = button.alpha = 0;
set alpha to 1
button.alpha = 1;
and check for rectangle.width , rectangle.height
last thing, check for textMC.hasLink() if its true or not. If its true, there is another problem with your code that is not related to this sample code.
Illogical answer:
Replaced stage.addChildAt(page,i+1); with stage.addChild(page);.
I was clutching at straws. Have spent FAR too long working on this blip, but it works! I don't know WHY it works, and at this point I don't care; IT WORKS!!! (sorry for the unprofessionalism however I have spent two and a half days working on this and have just got it working!)
If someone wants to explain why it works, feel free. I would VERY much prefer to learn why this occurs that struggle to work around it.

html data in a string make clickable html link AS3/Flex

I have a scenario that I get an string with html data, this is not just html data it's an email (outlook) saved as an html file and dropped in the string.
Now this string needs to be formatted to an html document and should be a clickable link in a datagrid. So when I click on the link, the HTML document should pop-up and should gave me a nice HTML page that is readable for the normal users. I hope it's a bit clear what I want o_0.
I don't know where to start.
You can download the example html from here: http://www.mediafire.com/?b2gfwymw70ynxir
Thanks!
---edit
Hopefully I can explain it a little bit better. I need to create an link and when they click on it they get an HTML page.
The string variable has HTML data in it, to be precise, the source data of the HTML example above.
example:
public var html:String = source_code_of_example_file;
The entire source code of the HTML page is in my variable html. Now I need to make this an link and when they click on it, they will get the html page (as pop-up) on the fly.
You can use the htmlText property and then specify a CSS to perform the proper formatting:
<mx:TextArea id="resourceText" height="100%" width="100%"
styleName="resourceText" editable="false"
styleSheet="{resourceStyleSheet}" htmlText="{html}"/>
To read in the style sheet I declare it in the model:
public var resourceStyleSheet : StyleSheet;
It gets read in from an external file:
private function loadCSS():void {
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, cssCompleteHandler);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
try {
urlLoader.load(new URLRequest("folder/base-html.css"));
} catch (error:Error) {
Alert.show("Unable to load requested document.");
}
}
private function cssCompleteHandler(event:Event):void {
// Convert text to style sheet.
var styleSheet:StyleSheet = new StyleSheet();
styleSheet.parseCSS(URLLoader(event.currentTarget).data);
// Set the style sheet.
model.resourceStyleSheet = styleSheet;
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
This will get it into the model, but then make sure resourceStyleSheet is bindable when you use it (I actually set a bindable variable on the view that I set to the model value.
It's not really clear what you want to do.
If your problem is you need to show HTML formatted text in flex there is a component which can do this
http://code.google.com/p/flex-iframe/
-- update after edit
If your intention is to open a html popup once the user clicks on the link you could use ExternalInterface to call a javascript function to do this.
Hope it Helps
There is no easy way to display HTML in a flex web application(this is a web application, right?). Like Xavi Colomer said you can use the Flex Iframe but is terribly slow, it requires you to change the display mode for your swf to opaque and this can cause more problems, depending on your application.
You could open a new page in the browser that will be used to display the HTML. Something like:
http://www.yourcooldomain.com/bla/displayTheHtml.php?oneTimeId=jhsfg765437gro734
More info on how to do this from flex here.
On the other side(server) I assume that you keep this html messages on a database(?) so displaying them using php(or whatever you are using :P) should be easy.
If you are gonna choose this path be careful about the security: oneTimeId in
displayTheHtml.php?oneTimeId=jhsfg765437gro734
should really be an one tyme only id.