All pastes #1425789 Raw Edit

Cross Domain Images in Userscrip

public javascript v1 · immutable
#1425789 ·published 2009-05-17 20:44 UTC
rendered paste body
function mime_from_data(data) // Simple function that checks for JPG, GIF and PNG from image data. Otherwise returns false.{	if('GIF'==data.substr(0,3))return 'image/gif';	else if('PNG'==data.substr(1,3))return 'image/png';	else if('JFIF'==data.substr(6,4))return 'image/jpg';	return false;};function data_string(data) // Generates the binary data string from character / multibyte data{	var data_string='';	for(var i=0,il=data.length;i<il;i++)data_string+=String.fromCharCode(data[i].charCodeAt(0)&0xff);	return data_string;};function load_image(){	GM_xmlhttpRequest({		method: 'GET',		url: 'http://www.domain.com/image.gif', // URL to image		overrideMimeType: 'text/plain; charset=x-user-defined',		onload: function(xhr)		{			var data = data_string(xhr.responseText);						// We can now do what we like with the data, E.g.			var base64_data = btoa(data); // Encode to base64 string						// We can then turn the Base64 string into a image using Data URL's ( http://en.wikipedia.org/wiki/Data_URI_scheme )			var data_url = 'data:' + mime_from_data(data) + ';base64,' + base64_data; // Make the data url						var image = new Image();			image.src = data_url;			document.body.appendChild(image); // Put image to page						// Or put the image to a cavas to manipulate			var canvas = unsafeWindow.document.createElement('canvas'); // Canvas is created in unsafeWindow context to aviod security issues			canvas.getContext('2d').drawImage(image,0,0); // Put image to canvas						// Or we can send the image data to a server			GM_xmlhttpRequest({				method:'POST',				headers:{'Content-type':'application/x-www-form-urlencoded'},				url:'http://www.domain.com/process.php', // URL to script				data:'image_data='+encodeURIComponent(base64_data),				onload:function(xhr)				{					// You can then decode the base64 data and write it to a file using PHP etc.					return;				}			});			return;		}	});	return;};window.addEventListener('load_image',load_image,false); // Make sure image has properly loaded