I've been trying really hard on this with no results, hope someone could help me out.
What I have is an HTML page with a ActionScript2 SWF object embedded. The SWF is a static sprite that gets dynamic text from the javascript. So basically looks like an image.
I want to print out the whole page HTML + SWF included, but as expected on the possition of the SWF object appears a blank square.
I print the page using javascript window.print();
Is there anyway to take a snapshot of the SWF or render it like an image? to show it on the print preview and on the printed document?
The size of the flash object is 600x381px;
Thank you!
Sorry guys、but I finally came up with a solution.
Thanks for having a look anyways.
What I first did is to convert the flash file from ActionScript2 to ActionScript3 to be able to use the as3corelib of Mike Chambers https://github.com/mikechambers/as3corelib.
From this library I used the JGPEncoder as seen below
import flash.external.ExternalInterface;
import flash.display.JPEGEncoderOptions;
import com.adobe.images.JPGEncoder;
import flash.display.BitmapData;
import flash.utils.ByteArray;
import flash.display.Bitmap;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.Event;
function snapShot(){
var imgBM:Bitmap;
var myBitmapData:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
myBitmapData.draw(stage);
imgBM=new Bitmap(myBitmapData);
addChild(imgBM);
var imgBA:ByteArray;
var jpgEncoder:JPGEncoder = new JPGEncoder(90);
//-------Send image to php
imgBA = jpgEncoder.encode(myBitmapData);
var sendHeader:URLRequestHeader = new URLRequestHeader('Content-type', 'application/octet-stream');
var sendReq:URLRequest = new URLRequest("parseimg.php");
sendReq.requestHeaders.push(sendHeader);
sendReq.method = URLRequestMethod.POST;
sendReq.data = imgBA;
var sendLoader:URLLoader = new URLLoader;
sendLoader.addEventListener(Event.COMPLETE, imageSentHandler);
sendLoader.load(sendReq);
}
var imagePath:String;
function imageSentHandler(event:Event):void {
var dataStr:String = event.currentTarget.data.toString();
var resultVars:URLVariables = new URLVariables();
resultVars.decode(dataStr);
imagePath = "http://" + resultVars.base + resultVars.filename;
}
The next step was to create the php that receives the ByteArray and creates the image file on the server.
<?php
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
$filename = "your_image_name.jpg";
$fp = fopen( $filename,"wb");
fwrite( $fp, $GLOBALS[ 'HTTP_RAW_POST_DATA' ] );
fclose( $fp );
echo "filename=".$filename."&base=".$_SERVER["HTTP_HOST"].dirname($_SERVER["PHP_SELF"]); } ?>
Finally and with the image already in a folder on the server, I just had to hide the Embedded flash object using CSS, and show up the image instead.
I got this using jquery on document.ready
var d = new Date();
setTimeout(function(){
$("#imgflash").attr("src", "your_image_name.jpg?"+d.getTime());
setTimeout("window.print();", 200);
},1000);
As I'm pretty new on ActionScript and Flash, any improvements on this code are kindly accepted.
Related
I have a requirement in wp8, where the picture selected by the user needs to be shown in the browser. To browse and select the photo, I am using photo chooser task.
I am able to get the physical location of the selected image, but on passing the same to JavaScript from c# its not displaying the image.
On googling came across the following link How to access isolated storage file from HTML or Javascript for Windows Phone and PhoneGap Application But it did not solve my issue.
For reference, the location of the image I am using was:
C:\Data\Users\DefApps\AppData{FA586990-6E21-0130-BF9E-3C075409010C}\Local\sample_photo_00.jpg
This is my Javascript code:
function myPicture(data) {
document.getElementById("capturedImage").src = data.imageUri;
alert("data.imageUri " + document.getElementById("capturedImage").src );
var width = data.imageWidth;
var height = data.imageHeight;
alert("image width" + width );
alert("image height" + height );
}
And this is my C# code:
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
string[] picList = Directory.GetFiles(localFolder.Path, "*.jpg");
foreach (string DeleteFile in picList) {
File.Delete(DeleteFile);
}
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
send (storageFile.Path);
Now send function should add MyHTML in picture.
You can call JavaScript function from C# by WebBrowser.InvokeScript and send image in args parameter. But args is string(s), so you will have to encode your image to string using some algorithm... Base64 for example:
string ImageToBase64String(Image image)
{
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, image.RawFormat);
return Convert.ToBase64String(stream.ToArray());
}
}
You will get some long string like this iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
On other side - in the JavaScript function you calling you will get that Base64 string and use it like this as src attribute of img element:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" />
More info about data uri scheme.
UPDATE: The easer solution. I think you can send your image path, width and height:
ImageProperties properties = await storageFile.Properties.GetImagePropertiesAsync();
webBrowser.InvokeScript("myPicture", storageFile.Path, (string)properties.Width, (string)properties.Height);
function myPicture(src, width, height) {
document.getElementById("capturedImage").src = src;
alert("data.imageUri " + document.getElementById("capturedImage").src );
alert("image width" + width );
alert("image height" + height );
}
I’m making a random sentence generator for my English class. I’m close but because of my limited php and javascript knowledge I need to ask for help. I’m not bad at reading the code, I just get stuck writing it.
I want to use explode to break up a string of comma seperated values. The string is a mix of English and Spanish, on the .txt file they would seperated like:
The book, El libro
The man, El hombre
The woman, La mujer
etc.
I would like to break these two values into an array and display them in separate places on my web page.
I`m going to use a random text generator script that I found, it’s working great with no problems. I just need to modify it using explode to read, separate the values into an array, and be able to display the separate values of the array.
<?php
/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';
/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;
/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;
// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}
// Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}
// If we have any text choose a random one, otherwise show 'No text to choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
}
// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
// Set the correct MIME type
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
}
else
{
echo $txt;
}
?>
The script that displays the result:
<script type="text/javascript" src="rantex.php?type=1"></script>
Can someone please help me modify the rantex.php file so that I can use explode to separate the different comma separated values, and use a different script to call them in different places on my web page?
Thank you, and please excuse my noobness.
The following seems unnecessary, since file() will have already removed new line characters:
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
To break your line, you may instead use:
list($english, $spanish) = explode(', ', trim($txt));
It seems you are trying to use PHP to serve a static page with some random sentences, right? So why not use PHP to serve valid JSON, and handle to display logic on the client?
Heres a quick implementation.
// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);
// Build an array (break on every line break)
$sentences = explode("\n", $source);
// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) {
return $item !== "";
});
// Build a hashmap of the array
$pairs = array_map(function($item) {
return ['sentence' => $item];
}, $filtered);
// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);
Now you can let the client handle the rest, with some basic JavaScript.
// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];
// Finally display it
random.sentence
[edit]
You can get the JSON data to client in many ways, but if you don't want to use something like Ajax, you could simply just dump the contents on your webpage, then use JavaScript to update the random sentence, from the global window object.
// Inside your php page
<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>
<script>
var sentences = <?= json_encode($pairs); ?>;
var random = sentences[Math.floor(Math.random() * sentences.length)];
var elspa = document.getElementById('spanish');
var eleng = document.getElementById('english');
elspa.innerText = random.sentence.split(',')[1];
eleng.innerText = random.sentence.split(',')[0];
</script>
Ok, so I have this figured out, I take 0 credit because I paid someone to do it. Special thanks to #stormpat for sending me in the right direction, if not for him I wouldn't have looked at this from a JSON point of view.
The .PHP file is like so:
<?php
$f_contents = file('quotes.txt');
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];
echo json_encode($data);
?>
On the .HTML page in the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
(function ($) {
$(function()
{
function load_random_data() {
$.get('random_line.php', function(data) {
var data = $.parseJSON(data);
$('#random_english').text(data.eng);
$('#random_spanish').text(data.esp);
});
}
load_random_data();
$('#get_random').click(function(e){
e.preventDefault();
load_random_data();
});
});
})(jQuery);
</script>
This splits the different variables into classes, so to call them into my html page I call them by their class, for instance I wanted to drop the variable into a table cell so I gave the individual td cell a class:
<td id="random_spanish"></td>
<td id="random_english"></td>
Plus as a bonus the coder threw in a nifty button to refresh the json classes:
<input type="button" value="Get random" id="get_random" />
So now I don`t have to have my students refresh the whole web page, they can just hit the button and refresh the random variables.
Thanks again everyone!
I want to know how to read text file and get the information to a javascript code.
What I mean is,
If I have text file contained with youtube Video-ID and Title
ID:youtubeVideoID1 "Title1"
ID:youtubeVideoID2 "Title2"
ID:youtubeVideoID3 "Title3"
ID:youtubeVideoID4 "Title4"
for example:
ID:gsjtg7m1MMM "X-Man Trailer!"
I want that my web (Index.html) will read the text-file's lines 1 by 1 ,by order,
and show me on my web embed of youtube videos like this:
<img width="143" alt="(TITLE)" src="http://img.youtube.com/vi/(VIDEO_ID)/hqdefault.jpg" >
It need to read and show only the lines that start with "ID:" and the first word after ID is the VIDEO_ID (so it should be a VAR) and after "space" comes the "TITLE" (and it can be a few words in some language) should be a var also..
so If I have only 5 rows in the text file with ID + TITLE, it will show me on the page, only 5 embed videos...
and if there is more, then more...
and if its javascript, what code I need to write on the web so it will show?
Thank You!
hope someone will help me with that..
This seems relatively simple.
First off we need to read the txt file:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
return allText;
}
}
}
rawFile.send(null);
}
var txt = readTextFile("path/to/txt/file.txt");
Then we need to parse the file, so assuming the file looks like above we could do it like this:
var split_txt = txt.split("ID:");
for(var i=0;i<split_txt.length;i++){
var id = split_txt[i].split(" \"")[0];
var title = split_txt[i].split(" \"")[1].slice(0,-1);
$("body").append("<img width=\"143\" alt=\""+title+"\" src=\"http://img.youtube.com/vi/"+id+"/hqdefault.jpg\" >");
}
You will require jQuery to run it.
Last time I asked for help in PHP and I got great response. Thanks to all of you for that. Now I am learning and creating website using MVC PHP. I want to ask you that can I create a custom function to use html tags? I am trying to remember that where I saw an example of it. Actually I've seen it before in and open source project.
It was like something this:
htmltag(script(src=address, type=javascript))
Its output was in html like:
<script src="address" type="javascript"></script>
So can I create something like this? I am trying to do this way:
public function script($var1, $var2){
$var1 = array(
'type'=>'',
'charset' => '',
'src' => ''
);
$var2 = false;
print("<script $var1>$var2</script>");
}
So can anyone guide me with this? Do I need to create class first? I will be waiting for your reply friends.
Javascript works with DOM, see the reference
function htmltag(name,atts) {
var tag = document.createElement(name);
for(var i in atts) tag.setAttribute(i, atts[i]);
return tag;
}
var img = htmltag("img", {
src: "https://kevcom.com/images/linux/linux.logo.2gp.jpg",
alt: "linux logo"
});
document.body.appendChild(img);
Note that img here is object (XML Node), not just plain text, so you can attach events on it etc. If you want to extract just the plain html code from it, use img.outerHTML. Test it on the fiddle.
Note: print is the equivalent of Ctrl+P in the browser :-) it is not the print equivalent in PHP.
In PHP you can use DOM::createElement and other methods from DOM which are quite similar to those from javascript. Personaly I prefer something more simple:
function tag($name,$atts="",$content="") {
$str_atts = "";
if(is_array($atts)) {
foreach($atts as $key=>$val) if(!($val===null || $val===false)) $str_atts.= " $key=\"$val\"";
} else $str_atts = " ".preg_replace("/=(?!\")(\S+)/m","=\"\\1\"",$atts);
if($name=="img" && !strpos($str_atts,"alt=")) $str_atts.= " alt=\"\"";
if(in_array($name,array("input","img","col","br","hr","meta"))) $name.= "/";
if(substr($name,-1)=="/") { $name = substr($name,0,-1); return "<{$name}{$str_atts}/>"; }
else return "<{$name}{$str_atts}>$content</$name>";
}
Examples
echo tag("p","class=foo id=bar1","hello");
echo tag("p",'class="foo" id="bar2"',"hey");
echo tag("p",array("class"=>"foo","id"=>"bar3"),"heya");
echo tag("img","src=https://kevcom.com/images/linux/linux.logo.2gp.jpg");
I'm trying to create a simple image slider on the front page of my drupal website. I wrote a module with the basic outline as follows
<?php
function slider_init(){
drupal_add_js(drupal_get_path('module', 'slider') .'/slider.js');
}
function slider_block($op = 'list', $delta = 0, $edit = array()) {
$block = array();
switch ($op) {
case "list":
// Generate listing of blocks from this module, for the admin/block page
$block[0]["info"] = t("slider");
break;
case "view":
// Generate content for blocks from this module
$block_content = "";
$block_content .= "hello";
//Query for the projects
$icons = db_query("SELECT * FROM {alumni_frontpage_projects}");
//Initiation arrays from each table column: title, description, url, icon link
$links = array();
$title = array();
$description = array();
$url = array();
//Generate arrays from each table column: title, description, url, icon link
while($icon_data = db_fetch_array($icons)){
$links[] = $icon_data['slider_image_location'];
$title[] = $icon_data['title'];
$description[]= $icon_data['description'];
$url[] = $icon_data['url'];
}
//Count elements in array and randomly choose one
$res = count($links)-1;
$seed = rand(0,$res);
//Generate HTML and Javascript of Slider
//Check that content isn't empty
if ($block_content == "") {
$block_content = t("Sorry No Content");
}
$block["content"] = $block_content;
break;
case "save":
break;
case "configure":
break;
}
return $block;
}
Now, everything is fine. I generate a block and I can place it wherever I want. Great. But I would really like to use javascript in this block so that I can pass the arrays and use onclick events to slide through some images from the arrays i queried. So I found out that I will have to pass the variables into javascript and I'll have to identify the javascript file i want to use in the module.
//add variable to the Javascript
drupal_add_js(array('slider_settings' => array('variable_name' => $variable_name)), 'setting');
//add Javascript file to module
drupal_add_js(drupal_get_path('module', 'slider') .'/slider.js');<br>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I put these in the hook_init BUT NOTHING HAPPENS!!!!! I tested to see basic alerts. If I put hard code into the _block, such as:
$block_content .= '
<script type="text/javascript">
var x
x = 50;
document.write(x); //prints the value of x
</script>';
Then I see '50' prints.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If I try to pass a variable to the hard coded script. That DOES NOT WORK either.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If I try to write 50 through the previous code, but from a separate file called slider.js which is in the same folder using "drupal_add_js(drupal_get_path('module', 'slider') .'/slider.js');", That DOES NOT WORK either (even though I'm not passing a variable)
So what the heck is going on!! Is it possible I'm missing some important core drupal files? Is there a way to trouble shoot this further?
Thanks!
drupal_add_js should work in hook_init().First Check whether your hook function is correctly named as ModuleName_init() or not.