Click here to Skip to main content
11,415,000 members (65,915 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: Javascript
how to get byte array to image in javascript
pls help me

Posted 16-Apr-13 2:04am
Zoltán Zörgő at 16-Apr-13 7:15am
Forget it

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

I normally wouldn't bother with such a poorly written question.
However, today it's just a matter of cut-n-paste of code I already have, so I may-as-well try to help.
Note - both approaches display the image, only the second makes it available for saving.

<!DOCTYPE html>
function newEl(tag){return document.createElement(tag);}
window.addEventListener('load', mInit, false);
// rbgData - 3 bytes per pixel - alpha-channel data not used (or valid)
function createImageFromRGBdata(rgbData, width, height)
	var mCanvas = newEl('canvas');
	mCanvas.width = width;
	mCanvas.height = height;
	var mContext = mCanvas.getContext('2d');
	var mImgData = mContext.createImageData(width, height);
	var srcIndex=0, dstIndex=0, curPixelNum=0;
	for (curPixelNum=0; curPixelNum<width*height;  curPixelNum++)
	{[dstIndex] = rgbData[srcIndex];		// r[dstIndex+1] = rgbData[srcIndex+1];	// g[dstIndex+2] = rgbData[srcIndex+2];	// b[dstIndex+3] = 255; // 255 = 0xFF - constant alpha, 100% opaque
		srcIndex += 3;
		dstIndex += 4;
	mContext.putImageData(mImgData, 0, 0);
	return mCanvas;

var rgbData = new Array(
0xff,0xff,0xff,  0xff,0xff,0xff,  0xff,0xff,0xff,  0xff,0xff,0xff,// white,white,white, white
0xff,0xff,0xff,  0xff,0x00,0x00,  0x00,0xff,0x00,  0xff,0xff,0xff,// white,  red,green, white
0xff,0xff,0xff,  0x00,0x00,0xff,  0xff,0xff,0x00,  0xff,0xff,0xff,// white, blue,yellow,white
0xff,0xff,0xff,  0xff,0xff,0xff,  0xff,0xff,0xff,  0xff,0xff,0xff // white,white,white, white
function mInit()
	// 1. - append data as a canvas element
	var mCanvas = createImageFromRGBdata(rgbData, 4, 4);
	mCanvas.setAttribute('style', "width:64px; height:64px; border:solid 1px black"); // make it large enough to be visible
	document.body.appendChild( mCanvas );
	// 2 - append data as a (saveable) image
	var mImg = newEl("img");
	var imgDataUrl = mCanvas.toDataURL();	// make a base64 string of the image data (the array above)
	mImg.src = imgDataUrl;
	mImg.setAttribute('style', "width:64px; height:64px; border:solid 1px black"); // make it large enough to be visible

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 9,160
1 OriginalGriff 7,487
2 Maciej Los 3,710
3 Abhinav S 3,298
4 Peter Leow 3,084

Advertise | Privacy | Mobile
Web01 | 2.8.150427.4 | Last Updated 16 Apr 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100