Skip to content

Instantly share code, notes, and snippets.

@GerHobbelt
Created July 24, 2012 23:02
Show Gist options
  • Save GerHobbelt/3173233 to your computer and use it in GitHub Desktop.
Save GerHobbelt/3173233 to your computer and use it in GitHub Desktop.
d3.js: load Adobe Photoshop ASE color palette file to color graph
# Editor backup files
*.bak
*~

Straight from Adobe Photoshop to D3.js …… ? 8

Showcases the Adobe.ASE.load.js file which can load a Photoshop ASE color palette file from the server and convert it to both a standard JS object hierarchy (which includes the group and color names) and a flattened array which can be fed directly to d3.scale.ordinal().range(...) for quick & easy as a color palette for d3.js visualizations.

Using this JavaScript software, you or your designer can concoct any color palette in tools such as Adobe Photoshop, place the exported Adobe ASE file on any server as a static file and you're Up & Go!

What's the use?

ZERO server-side / developer / tool effort required to convert artist-created color palettes before those are usable in your web projects, particularly when you're using D3.js to visualize your data.

Adobe Photoshop > Swatches > Save Swatches for Exchange > upload to server (static content) > use in any d3 visualization

Any hot tips?

Certainly. Get your derrière over to the Adobe Kuler web site to peruse a zillion color palettes created by the community.

And if that's not enough, there's a lot of color tools out there which produce ASE files for you to download: anyone who exports color templates for use in Photoshop is producing ASE files!

Technology

The code uses the excellent jDataview.js from Christopher Chedeau.

Using this is very simple:

  • make sure you've loaded both the jDataview.js and Adobe.ASE.load.js scripts

  • fetch the ASE file from your web store (server) using the API call: adobe.ase.load(file, callback) where callback can be any function you specify. The callback function will receive up to 3 arguments: (palette, flat_rgb_set, error_msg).

    • palette: the JavaScript object structure which contains all the info, including color and group names, which was contained in the ASE file. See the callback.palette.arg.format.md file for the object hierarchy/format specification.

    • flat_rgb_set: a flat array containing one HTML color string in #RRGGBB format for each color in the palette

    • error_msg: optional 3rd argument which will contain an error message when something went horribly wrong. In case of errors, both palette and flat_rgb_set are set to null.

/*
Copyright (c) 2012, Ger Hobbelt ([email protected])
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name Ger Hobbelt may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function(){
/*
This software assumes that jDataview.js has been loaded alongside.
jDataview.js is (c) Copyright Christopher Chedeau and is available at
https://github.com/vjeux/jDataView
and
http://blog.vjeux.com/2011/javascript/jdataview-read-binary-file.html
Info sources consulted while preparing/building this software:
Adobe ASE (Color Swatches) format:
http://www.selapa.net/swatches/colors/fileformats.php
http://iamacamera.org/default.aspx?id=109
CMYK / LAB to RGB:
http://www.easyrgb.com/index.php?X=MATH&H=12#text12
http://www.codeproject.com/Articles/4488/XCmyk-CMYK-to-RGB-Calculator-with-source-code
Loading binary files in JavaScript:
https://developer.mozilla.org/en/using_xmlhttprequest#Receiving_binary_data
http://blog.vjeux.com/2011/javascript/jdataview-read-binary-file.html
http://blog.vjeux.com/2010/javascript/javascript-binary-reader.html
http://codereview.stackexchange.com/questions/3569/pack-and-unpack-bytes-to-strings
http://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string
*/
adobe =
{
ase: {version: "0.0.1"} // semver
};
adobe.ase.load = function(url, callback)
{
d3.xhr(url, 'text/plain; charset=x-user-defined', function(req)
{
if (req)
{
console.log(req);
var version_major, version_minor, count, i, view, palette = {}, flattened = [];
try
{
view = new jDataView(req.response, 0, undefined, false); // big-endian format
}
catch(e)
{
view = null;
}
if (!view ||
"ASEF" !== view.getString(4) ||
(version_major = view.getInt16()) < 1 ||
(version_minor = view.getInt16()) < 0 ||
(count = view.getInt32()) < 1)
{
callback(null, null, "illegal file format, not a ASE color palette file");
}
function rgb2str(rgb)
{
var r, g, b;
r = rgb[0].toString(16);
if (r.length < 2)
r = "0" + r;
g = rgb[1].toString(16);
if (g.length < 2)
g = "0" + g;
b = rgb[2].toString(16);
if (b.length < 2)
b = "0" + b;
return "#" + r + g + b;
}
function parse_utf16_Cstring(view)
{
var slen = view.getUint16();
var c, name = "", i = slen;
// ignore NUL sentinel at the end of the string
while (--i > 0) {
c = view.getUint16();
name += String.fromCharCode(c);
}
view.getUint16();
return name;
}
function parse_block(view, palette)
{
// parse block:
var i, id, len, slen, model, type, c, m, k, l, a, r, g, b, x, y, z, name, p;
while (--count >= 0)
{
id = view.getUint16();
switch (id)
{
default:
// illegal block; damaged ASE file?
callback(null, null, "unknown block type " + id.toString(16) + ": broken ASE color palette file");
return -1;
case 0xc001: // group start
len = view.getUint32();
name = parse_utf16_Cstring(view);
if (!palette.groups)
palette.groups = [];
palette.groups.push(p = {
name: name
});
if (parse_block(view, p))
return -1;
continue;
case 0xc002: // group end
view.getUint32(); // skip 0 length
return 0;
case 0x0001: // color
len = view.getUint32();
name = parse_utf16_Cstring(view);
model = view.getString(4);
if (!palette.colors)
palette.colors = [];
palette.colors.push(p = {
name: name,
model: model
});
switch (model)
{
case "CMYK":
c = view.getFloat32();
m = view.getFloat32();
y = view.getFloat32();
k = view.getFloat32();
p.cmyk = [c, m, y, k];
if (k >= 1)
{
//Black
r = g = b = 0;
}
else
{
//CMYK and CMY values from 0 to 1
c = c * (1 - k) + k;
m = m * (1 - k) + k;
y = y * (1 - k) + k;
//CMY values from 0 to 1
//RGB results from 0 to 255
r = (1 - c);
g = (1 - m);
b = (1 - y);
r = Math.min(255, Math.max(0, Math.round(r * 255)));
g = Math.min(255, Math.max(0, Math.round(g * 255)));
b = Math.min(255, Math.max(0, Math.round(b * 255)));
}
flattened.push(rgb2str(p.html_rgb = [r, g, b]));
break;
case "RGB ":
r = view.getFloat32();
g = view.getFloat32();
b = view.getFloat32();
p.rgb = [r, g, b]; // also keep the raw RGB
r = Math.min(255, Math.max(0, Math.round(r * 255)));
g = Math.min(255, Math.max(0, Math.round(g * 255)));
b = Math.min(255, Math.max(0, Math.round(b * 255)));
flattened.push(rgb2str(p.html_rgb = [r, g, b]));
break;
case "LAB ":
l = view.getFloat32();
a = view.getFloat32();
b = view.getFloat32();
p.lab = [l, a, b];
// Photoshop CS5.5 saves these as perunage (0..1), value, value. So we need to adjust L before commencing:
l *= 100;
// CIE-L*ab -> XYZ
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
if (Math.pow(y, 3) > 0.008856)
y = Math.pow(y, 3);
else
y = (y - 16 / 116) / 7.787;
if (Math.pow(x, 3) > 0.008856)
x = Math.pow(x, 3);
else
x = (x - 16 / 116) / 7.787;
if (Math.pow(z, 3) > 0.008856)
z = Math.pow(z, 3);
else
z = (z - 16 / 116) / 7.787;
x = 95.047 * x; //ref_X = 95.047 Observer= 2°, Illuminant= D65
y = 100.000 * y; //ref_Y = 100.000
z = 108.883 * z; //ref_Z = 108.883
// XYZ -> RGB
x = x / 100; //X from 0 to 95.047 (Observer = 2°, Illuminant = D65)
y = y / 100; //Y from 0 to 100.000
z = z / 100; //Z from 0 to 108.883
r = x * 3.2406 + y * -1.5372 + z * -0.4986;
g = x * -0.9689 + y * 1.8758 + z * 0.0415;
b = x * 0.0557 + y * -0.2040 + z * 1.0570;
if (r > 0.0031308)
r = 1.055 * Math.pow(r, 1 / 2.4) - 0.055;
else
r = 12.92 * r;
if (g > 0.0031308)
g = 1.055 * Math.pow(g, 1 / 2.4) - 0.055;
else
g = 12.92 * g;
if (b > 0.0031308)
b = 1.055 * Math.pow(b, 1 / 2.4) - 0.055;
else
b = 12.92 * b;
r = Math.min(255, Math.max(0, Math.round(r * 255)));
g = Math.min(255, Math.max(0, Math.round(g * 255)));
b = Math.min(255, Math.max(0, Math.round(b * 255)));
flattened.push(rgb2str(p.html_rgb = [r, g, b]));
break;
case "GRAY":
g = view.getFloat32();
p.gray = g;
g = Math.min(255, Math.max(0, Math.round(g * 255)));
flattened.push(rgb2str(p.html_rgb = [g, g, g]));
break;
default:
callback(null, null, "unknown color model " + model + ": broken ASE color palette file");
return -1;
}
type = view.getUint16();
p.color_type = type; // (0 => Global, 1 => Spot, 2 => Normal)
continue;
}
}
return 0;
}
if (!parse_block(view, palette))
callback(palette, flattened);
} else {
callback(null, null, "I/O error: could not load ASE palette file");
}
});
};
})();

palette structure layout

Exact copy of the ASE content. Grouping depends on the tools used to produced the ASE.

palette =
{
  groups: <Array of objects>,
  colors: <Array of objects>
}

colors and groups are optional elements, but each palette object should have at least one of them. When they exist in the object, they are non-empty arrays, i.e. carry at least 1 entry.

A group object is a palette with a name:

group =
{
  name: <string: name of the group>,

  groups: <Array of objects>,
  colors: <Array of objects>
}

and a color object contains a single color:

color =
{
  name:  <string: name of the color swatch>,
  model: <string(4): model string: 'CMYK', 'RGB ', 'LAB ', 'GRAY'>,
  type:  <number: 0 &#8658; Global, 1 &#8658; Spot, 2 &#8658; Normal>,

  cmyk: <Array of 4 float numbers: [C, M, Y, K], ranges [0 .. 1.0]>,
  rgb:  <Array of 3 float numbers: [R, G, B], ranges [0 .. 1.0]>,
  lab:  <Array of 3 float numbers: [L, A, B], L range [0 .. 1.0], A & B range cf. CIELAB D50>,
  gray: <float number, range [0 .. 1.0]>,

  html_rgb:  <string: '#RRGGBB' formatted, converted color>
}

The cmyk, rgb, gray and lab fields are optional: only the one corresponding to the given color model will be present. This field will contain the values as stored in the ASE file.

The html_rgb field is always present; this field is used to simplify user code / prevent code duplication, as the various colorspace conversions are done inside the ASE loader code. (Note: the flat_rgb_set color array passed to the user callback as the second callback argument contains these values too.)

<!DOCTYPE html>
<html>
<head>
<script src="http://mbostock.github.com/d3/d3.v2.js"></script>
<script src="jdataview.js"></script>
<script src="Adobe.ASE.load.js"></script>
<title>Show ASE color palettes from Adobe Photoshop / Adobe Kuler</title>
<style>
</style>
</head>
<body>
<img style="position:absolute;top:0;right:0;border:0;" width="149" height="149" src="../forkme.png" alt="Fork me on GitHub">
<div>
<label>Pick a color palette:
<select id="pallete_picker">
<option value="-" > D3 internal: category10</option>
<option value="dragon.ase" > Dragon NS</option>
<option value="HKS.Z.process.ase" > Adobe Photoshop: HKS Z (process)</option>
<option value="adobe.kuler---5.Star.ase" > Adobe Kuler: 5 Star</option>
<option value="adobe.kuler---a.mix.of.misty.blue.with.purple.ase" > Adobe Kuler: a mix of misty blue with purple</option>
<option value="adobe.kuler---A.Touch.of.Mink.ase" > Adobe Kuler: A Touch of Mink</option>
<option value="adobe.kuler---AEC.New.3.ase" > Adobe Kuler: AEC New 3</option>
<option value="adobe.kuler---Ex.Removal.Connection.ase" > Adobe Kuler: Ex Removal Connection</option>
<option value="adobe.kuler---I.want.Color.Wheels.for.my.Car.ase" > Adobe Kuler: I want Color Wheels for my Car</option>
<option value="adobe.kuler---Streetlamp.ase" > Adobe Kuler: Streetlamp</option>
<option value="adobe.kuler---The.Tough.Go.Shopping.ase" > Adobe Kuler: The Tough Go Shopping</option>
<option value="LAB.colorspace.test.ase" > (ugly) LAB colorspace test swatch set</option>
</select>
</label>
</div>
<svg>
</svg>
<script type="text/javascript" >
var h=450
,w=900
,margin=20
,color = d3.scale.category10()
,blocks = d3.range(10 * 20);
var svg = d3.select("svg")
.attr("height",h)
.attr("width",w);
svg.selectAll("rect")
.data(blocks)
.enter()
.append("rect")
.attr("x", function(d) { return (d % 20) * 44 + Math.floor((d % 20) / 5) * 4 + 3; })
.attr("y", function(d) { return Math.floor(d / 20) * 44 + 3; })
.attr("width", 40)
.attr("height", 40)
.style("stroke", "black")
.style("fill", function(d) { return color(d); });
var picker = d3.select("#pallete_picker")
.on("change", function() {
console.log("click", arguments);
var file = picker.node().value;
if (file === "-")
{
color = d3.scale.category10();
svg.selectAll("rect")
.style("fill", function(d) { return color(d); });
}
else
{
adobe.ase.load(file, function(palette, flat_rgb_set, error_msg) {
console.log("ASE: ", palette, flat_rgb_set, error_msg);
color = d3.scale.ordinal().range(flat_rgb_set);
svg.selectAll("rect")
.style("fill", function(d) { return color(d); });
});
}
});
</script>
</body>
</html>
//
// jDataView by Vjeux - Jan 2010
//
// A unique way to read a binary file in the browser
// http://github.com/vjeux/jDataView
// http://blog.vjeux.com/ <[email protected]>
//
(function (global) {
var compatibility = {
ArrayBuffer: typeof ArrayBuffer !== 'undefined',
DataView: typeof DataView !== 'undefined' &&
('getFloat64' in DataView.prototype || // Chrome
'getFloat64' in new DataView(new ArrayBuffer(1))), // Node
// NodeJS Buffer in v0.5.5 and newer
NodeBuffer: typeof Buffer !== 'undefined' && 'readInt16LE' in Buffer.prototype
};
var dataTypes = {
'Int8': 1,
'Int16': 2,
'Int32': 4,
'Uint8': 1,
'Uint16': 2,
'Uint32': 4,
'Float32': 4,
'Float64': 8
};
var nodeNaming = {
'Int8': 'Int8',
'Int16': 'Int16',
'Int32': 'Int32',
'Uint8': 'UInt8',
'Uint16': 'UInt16',
'Uint32': 'UInt32',
'Float32': 'Float',
'Float64': 'Double'
};
var jDataView = function (buffer, byteOffset, byteLength, littleEndian) {
if (!(this instanceof jDataView)) {
throw new Error("jDataView constructor may not be called as a function");
}
this.buffer = buffer;
// Handle Type Errors
if (!(compatibility.NodeBuffer && buffer instanceof Buffer) &&
!(compatibility.ArrayBuffer && buffer instanceof ArrayBuffer) &&
typeof buffer !== 'string') {
throw new TypeError('jDataView buffer has an incompatible type');
}
// Check parameters and existing functionnalities
this._isArrayBuffer = compatibility.ArrayBuffer && buffer instanceof ArrayBuffer;
this._isDataView = compatibility.DataView && this._isArrayBuffer;
this._isNodeBuffer = compatibility.NodeBuffer && buffer instanceof Buffer;
// Default Values
this._littleEndian = littleEndian === undefined ? false : littleEndian;
var bufferLength = this._isArrayBuffer ? buffer.byteLength : buffer.length;
if (byteOffset === undefined) {
byteOffset = 0;
}
this.byteOffset = byteOffset;
if (byteLength === undefined) {
byteLength = bufferLength - byteOffset;
}
this.byteLength = byteLength;
if (!this._isDataView) {
// Do additional checks to simulate DataView
if (typeof byteOffset !== 'number') {
throw new TypeError('jDataView byteOffset is not a number');
}
if (typeof byteLength !== 'number') {
throw new TypeError('jDataView byteLength is not a number');
}
if (byteOffset < 0) {
throw new Error('jDataView byteOffset is negative');
}
if (byteLength < 0) {
throw new Error('jDataView byteLength is negative');
}
}
// Instanciate
if (this._isDataView) {
this._view = new DataView(buffer, byteOffset, byteLength);
this._start = 0;
}
this._start = byteOffset;
if (byteOffset + byteLength > bufferLength) {
throw new Error("jDataView (byteOffset + byteLength) value is out of bounds");
}
this._offset = 0;
// Create uniform reading methods (wrappers) for the following data types
if (this._isDataView) { // DataView: we use the direct method
for (var type in dataTypes) {
if (!dataTypes.hasOwnProperty(type)) {
continue;
}
(function(type, view){
var size = dataTypes[type];
view['get' + type] = function (byteOffset, littleEndian) {
// Handle the lack of endianness
if (littleEndian === undefined) {
littleEndian = view._littleEndian;
}
// Handle the lack of byteOffset
if (byteOffset === undefined) {
byteOffset = view._offset;
}
// Move the internal offset forward
view._offset = byteOffset + size;
return view._view['get' + type](byteOffset, littleEndian);
}
})(type, this);
}
} else if (this._isNodeBuffer && compatibility.NodeBuffer) {
for (var type in dataTypes) {
if (!dataTypes.hasOwnProperty(type)) {
continue;
}
var name;
if (type === 'Int8' || type === 'Uint8') {
name = 'read' + nodeNaming[type];
} else if (littleEndian) {
name = 'read' + nodeNaming[type] + 'LE';
} else {
name = 'read' + nodeNaming[type] + 'BE';
}
(function(type, view, name){
var size = dataTypes[type];
view['get' + type] = function (byteOffset, littleEndian) {
// Handle the lack of endianness
if (littleEndian === undefined) {
littleEndian = view._littleEndian;
}
// Handle the lack of byteOffset
if (byteOffset === undefined) {
byteOffset = view._offset;
}
// Move the internal offset forward
view._offset = byteOffset + size;
return view.buffer[name](view._start + byteOffset);
}
})(type, this, name);
}
} else {
for (var type in dataTypes) {
if (!dataTypes.hasOwnProperty(type)) {
continue;
}
(function(type, view){
var size = dataTypes[type];
view['get' + type] = function (byteOffset, littleEndian) {
// Handle the lack of endianness
if (littleEndian === undefined) {
littleEndian = view._littleEndian;
}
// Handle the lack of byteOffset
if (byteOffset === undefined) {
byteOffset = view._offset;
}
// Move the internal offset forward
view._offset = byteOffset + size;
if (view._isArrayBuffer && (view._start + byteOffset) % size === 0 && (size === 1 || littleEndian)) {
// ArrayBuffer: we use a typed array of size 1 if the alignment is good
// ArrayBuffer does not support endianess flag (for size > 1)
return new global[type + 'Array'](view.buffer, view._start + byteOffset, 1)[0];
} else {
// Error checking:
if (typeof byteOffset !== 'number') {
throw new TypeError('jDataView byteOffset is not a number');
}
if (byteOffset + size > view.byteLength) {
throw new Error('jDataView (byteOffset + size) value is out of bounds');
}
return view['_get' + type](view._start + byteOffset, littleEndian);
}
}
})(type, this);
}
}
};
if (compatibility.NodeBuffer) {
jDataView.createBuffer = function () {
var buffer = new Buffer(arguments.length);
for (var i = 0; i < arguments.length; ++i) {
buffer[i] = arguments[i];
}
return buffer;
}
} else if (compatibility.ArrayBuffer) {
jDataView.createBuffer = function () {
var buffer = new ArrayBuffer(arguments.length);
var view = new Int8Array(buffer);
for (var i = 0; i < arguments.length; ++i) {
view[i] = arguments[i];
}
return buffer;
}
} else {
jDataView.createBuffer = function () {
return String.fromCharCode.apply(null, arguments);
}
}
jDataView.prototype = {
compatibility: compatibility,
// Helpers
getString: function (length, byteOffset) {
var value;
// Handle the lack of byteOffset
if (byteOffset === undefined) {
byteOffset = this._offset;
}
// Error Checking
if (typeof byteOffset !== 'number') {
throw new TypeError('jDataView byteOffset is not a number');
}
if (length < 0 || byteOffset + length > this.byteLength) {
throw new Error('jDataView length or (byteOffset+length) value is out of bounds');
}
if (this._isNodeBuffer) {
value = this.buffer.toString('ascii', this._start + byteOffset, this._start + byteOffset + length);
}
else {
value = '';
for (var i = 0; i < length; ++i) {
var char = this.getUint8(byteOffset + i);
value += String.fromCharCode(char > 127 ? 65533 : char);
}
}
this._offset = byteOffset + length;
return value;
},
getChar: function (byteOffset) {
return this.getString(1, byteOffset);
},
tell: function () {
return this._offset;
},
seek: function (byteOffset) {
if (typeof byteOffset !== 'number') {
throw new TypeError('jDataView byteOffset is not a number');
}
if (byteOffset < 0 || byteOffset > this.byteLength) {
throw new Error('jDataView byteOffset value is out of bounds');
}
return this._offset = byteOffset;
},
// Compatibility functions on a String Buffer
_endianness: function (byteOffset, pos, max, littleEndian) {
return byteOffset + (littleEndian ? max - pos - 1 : pos);
},
_getFloat64: function (byteOffset, littleEndian) {
var b0 = this._getUint8(this._endianness(byteOffset, 0, 8, littleEndian)),
b1 = this._getUint8(this._endianness(byteOffset, 1, 8, littleEndian)),
b2 = this._getUint8(this._endianness(byteOffset, 2, 8, littleEndian)),
b3 = this._getUint8(this._endianness(byteOffset, 3, 8, littleEndian)),
b4 = this._getUint8(this._endianness(byteOffset, 4, 8, littleEndian)),
b5 = this._getUint8(this._endianness(byteOffset, 5, 8, littleEndian)),
b6 = this._getUint8(this._endianness(byteOffset, 6, 8, littleEndian)),
b7 = this._getUint8(this._endianness(byteOffset, 7, 8, littleEndian)),
sign = 1 - (2 * (b0 >> 7)),
exponent = ((((b0 << 1) & 0xff) << 3) | (b1 >> 4)) - (Math.pow(2, 10) - 1),
// Binary operators such as | and << operate on 32 bit values, using + and Math.pow(2) instead
mantissa = ((b1 & 0x0f) * Math.pow(2, 48)) + (b2 * Math.pow(2, 40)) + (b3 * Math.pow(2, 32)) +
(b4 * Math.pow(2, 24)) + (b5 * Math.pow(2, 16)) + (b6 * Math.pow(2, 8)) + b7;
if (exponent === 1024) {
if (mantissa !== 0) {
return NaN;
} else {
return sign * Infinity;
}
}
if (exponent === -1023) { // Denormalized
return sign * mantissa * Math.pow(2, -1022 - 52);
}
return sign * (1 + mantissa * Math.pow(2, -52)) * Math.pow(2, exponent);
},
_getFloat32: function (byteOffset, littleEndian) {
var b0 = this._getUint8(this._endianness(byteOffset, 0, 4, littleEndian)),
b1 = this._getUint8(this._endianness(byteOffset, 1, 4, littleEndian)),
b2 = this._getUint8(this._endianness(byteOffset, 2, 4, littleEndian)),
b3 = this._getUint8(this._endianness(byteOffset, 3, 4, littleEndian)),
sign = 1 - (2 * (b0 >> 7)),
exponent = (((b0 << 1) & 0xff) | (b1 >> 7)) - 127,
mantissa = ((b1 & 0x7f) << 16) | (b2 << 8) | b3;
if (exponent === 128) {
if (mantissa !== 0) {
return NaN;
} else {
return sign * Infinity;
}
}
if (exponent === -127) { // Denormalized
return sign * mantissa * Math.pow(2, -126 - 23);
}
return sign * (1 + mantissa * Math.pow(2, -23)) * Math.pow(2, exponent);
},
_getInt32: function (byteOffset, littleEndian) {
var b = this._getUint32(byteOffset, littleEndian);
return b > Math.pow(2, 31) - 1 ? b - Math.pow(2, 32) : b;
},
_getUint32: function (byteOffset, littleEndian) {
var b3 = this._getUint8(this._endianness(byteOffset, 0, 4, littleEndian)),
b2 = this._getUint8(this._endianness(byteOffset, 1, 4, littleEndian)),
b1 = this._getUint8(this._endianness(byteOffset, 2, 4, littleEndian)),
b0 = this._getUint8(this._endianness(byteOffset, 3, 4, littleEndian));
return (b3 * Math.pow(2, 24)) + (b2 << 16) + (b1 << 8) + b0;
},
_getInt16: function (byteOffset, littleEndian) {
var b = this._getUint16(byteOffset, littleEndian);
return b > Math.pow(2, 15) - 1 ? b - Math.pow(2, 16) : b;
},
_getUint16: function (byteOffset, littleEndian) {
var b1 = this._getUint8(this._endianness(byteOffset, 0, 2, littleEndian)),
b0 = this._getUint8(this._endianness(byteOffset, 1, 2, littleEndian));
return (b1 << 8) + b0;
},
_getInt8: function (byteOffset) {
var b = this._getUint8(byteOffset);
return b > Math.pow(2, 7) - 1 ? b - Math.pow(2, 8) : b;
},
_getUint8: function (byteOffset) {
if (this._isArrayBuffer) {
return new Uint8Array(this.buffer, byteOffset, 1)[0];
}
else if (this._isNodeBuffer) {
return this.buffer[byteOffset];
} else {
return this.buffer.charCodeAt(byteOffset) & 0xff;
}
}
};
if (typeof jQuery !== 'undefined' && jQuery.fn.jquery >= "1.6.2") {
var convertResponseBodyToText = function (byteArray) {
// http://jsperf.com/vbscript-binary-download/6
var scrambledStr;
try {
scrambledStr = IEBinaryToArray_ByteStr(byteArray);
} catch (e) {
// http://stackoverflow.com/questions/1919972/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie
// http://miskun.com/javascript/internet-explorer-and-binary-files-data-access/
var IEBinaryToArray_ByteStr_Script =
"Function IEBinaryToArray_ByteStr(Binary)\r\n"+
" IEBinaryToArray_ByteStr = CStr(Binary)\r\n"+
"End Function\r\n"+
"Function IEBinaryToArray_ByteStr_Last(Binary)\r\n"+
" Dim lastIndex\r\n"+
" lastIndex = LenB(Binary)\r\n"+
" if lastIndex mod 2 Then\r\n"+
" IEBinaryToArray_ByteStr_Last = AscB( MidB( Binary, lastIndex, 1 ) )\r\n"+
" Else\r\n"+
" IEBinaryToArray_ByteStr_Last = -1\r\n"+
" End If\r\n"+
"End Function\r\n";
// http://msdn.microsoft.com/en-us/library/ms536420(v=vs.85).aspx
// proprietary IE function
window.execScript(IEBinaryToArray_ByteStr_Script, 'vbscript');
scrambledStr = IEBinaryToArray_ByteStr(byteArray);
}
var lastChr = IEBinaryToArray_ByteStr_Last(byteArray),
result = "",
i = 0,
l = scrambledStr.length % 8,
thischar;
while (i < l) {
thischar = scrambledStr.charCodeAt(i++);
result += String.fromCharCode(thischar & 0xff, thischar >> 8);
}
l = scrambledStr.length
while (i < l) {
result += String.fromCharCode(
(thischar = scrambledStr.charCodeAt(i++), thischar & 0xff), thischar >> 8,
(thischar = scrambledStr.charCodeAt(i++), thischar & 0xff), thischar >> 8,
(thischar = scrambledStr.charCodeAt(i++), thischar & 0xff), thischar >> 8,
(thischar = scrambledStr.charCodeAt(i++), thischar & 0xff), thischar >> 8,
(thischar = scrambledStr.charCodeAt(i++), thischar & 0xff), thischar >> 8,
(thischar = scrambledStr.charCodeAt(i++), thischar & 0xff), thischar >> 8,
(thischar = scrambledStr.charCodeAt(i++), thischar & 0xff), thischar >> 8,
(thischar = scrambledStr.charCodeAt(i++), thischar & 0xff), thischar >> 8);
}
if (lastChr > -1) {
result += String.fromCharCode(lastChr);
}
return result;
};
jQuery.ajaxSetup({
converters: {
'* dataview': function(data) {
return new jDataView(data);
}
},
accepts: {
dataview: "text/plain; charset=x-user-defined"
},
responseHandler: {
dataview: function (responses, options, xhr) {
// Array Buffer Firefox
if ('mozResponseArrayBuffer' in xhr) {
responses.text = xhr.mozResponseArrayBuffer;
}
// Array Buffer Chrome
else if ('responseType' in xhr && xhr.responseType === 'arraybuffer' && xhr.response) {
responses.text = xhr.response;
}
// Internet Explorer (Byte array accessible through VBScript -- convert to text)
else if ('responseBody' in xhr) {
responses.text = convertResponseBodyToText(xhr.responseBody);
}
// Older Browsers
else {
responses.text = xhr.responseText;
}
}
}
});
jQuery.ajaxPrefilter('dataview', function(options, originalOptions, jqXHR) {
// trying to set the responseType on IE 6 causes an error
if (jQuery.support.ajaxResponseType) {
if (!options.hasOwnProperty('xhrFields')) {
options.xhrFields = {};
}
options.xhrFields.responseType = 'arraybuffer';
}
options.mimeType = 'text/plain; charset=x-user-defined';
});
}
global.jDataView = (global.module || {}).exports = jDataView;
if (typeof module !== 'undefined') {
module.exports = jDataView;
}
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment