Code Monkey home page Code Monkey logo

blueimp / javascript-load-image Goto Github PK

View Code? Open in Web Editor NEW
4.4K 162.0 921.0 1.93 MB

Load images provided as File or Blob objects or via URL. Retrieve an optionally scaled, cropped or rotated HTML img or canvas element. Use methods to parse image metadata to extract IPTC and Exif tags as well as embedded thumbnail images, to overwrite the Exif Orientation value and to restore the complete image header after resizing.

Home Page: https://blueimp.github.io/JavaScript-Load-Image/

License: MIT License

CSS 2.24% JavaScript 93.75% HTML 3.82% Shell 0.19%

javascript-load-image's Introduction

JavaScript Load Image

A JavaScript library to load and transform image files.

Contents

Description

JavaScript Load Image is a library to load images provided as File or Blob objects or via URL. It returns an optionally scaled, cropped or rotated HTML img or canvas element.

It also provides methods to parse image metadata to extract IPTC and Exif tags as well as embedded thumbnail images, to overwrite the Exif Orientation value and to restore the complete image header after resizing.

Setup

Install via NPM:

npm install blueimp-load-image

This will install the JavaScript files inside ./node_modules/blueimp-load-image/js/ relative to your current directory, from where you can copy them into a folder that is served by your web server.

Next include the combined and minified JavaScript Load Image script in your HTML markup:

<script src="js/load-image.all.min.js"></script>

Or alternatively, choose which components you want to include:

<!-- required for all operations -->
<script src="js/load-image.js"></script>

<!-- required for scaling, cropping and as dependency for rotation -->
<script src="js/load-image-scale.js"></script>

<!-- required to parse meta data and to restore the complete image head -->
<script src="js/load-image-meta.js"></script>

<!-- required to parse meta data from images loaded via URL -->
<script src="js/load-image-fetch.js"></script>

<!-- required for rotation and cross-browser image orientation -->
<script src="js/load-image-orientation.js"></script>

<!-- required to parse Exif tags and cross-browser image orientation -->
<script src="js/load-image-exif.js"></script>

<!-- required to display text mappings for Exif tags -->
<script src="js/load-image-exif-map.js"></script>

<!-- required to parse IPTC tags -->
<script src="js/load-image-iptc.js"></script>

<!-- required to display text mappings for IPTC tags -->
<script src="js/load-image-iptc-map.js"></script>

Usage

Image loading

In your application code, use the loadImage() function with callback style:

document.getElementById('file-input').onchange = function () {
  loadImage(
    this.files[0],
    function (img) {
      document.body.appendChild(img)
    },
    { maxWidth: 600 } // Options
  )
}

Or use the Promise based API like this (requires a polyfill for older browsers):

document.getElementById('file-input').onchange = function () {
  loadImage(this.files[0], { maxWidth: 600 }).then(function (data) {
    document.body.appendChild(data.image)
  })
}

With async/await (requires a modern browser or a code transpiler like Babel or TypeScript):

document.getElementById('file-input').onchange = async function () {
  let data = await loadImage(this.files[0], { maxWidth: 600 })
  document.body.appendChild(data.image)
}

Image scaling

It is also possible to use the image scaling functionality directly with an existing image:

var scaledImage = loadImage.scale(
  img, // img or canvas element
  { maxWidth: 600 }
)

Requirements

The JavaScript Load Image library has zero dependencies, but benefits from the following two polyfills:

Browser support

Browsers which implement the following APIs support all options:

This includes (but is not limited to) the following browsers:

  • Chrome 32+
  • Firefox 29+
  • Safari 8+
  • Mobile Chrome 42+ (Android)
  • Mobile Firefox 50+ (Android)
  • Mobile Safari 8+ (iOS)
  • Edge 74+
  • Edge Legacy 12+
  • Internet Explorer 10+ *

* Internet Explorer requires a polyfill for the Promise based API.

Loading an image from a URL and applying transformations (scaling, cropping and rotating - except orientation:true, which requires reading meta data) is supported by all browsers which implement the HTMLCanvasElement interface.

Loading an image from a URL and scaling it in size is supported by all browsers which implement the img element and has been tested successfully with browser engines as old as Internet Explorer 5 (via IE11's emulation mode).

The loadImage() function applies options using progressive enhancement and falls back to a configuration that is supported by the browser, e.g. if the canvas element is not supported, an equivalent img element is returned.

API

Callback

Function signature

The loadImage() function accepts a File or Blob object or an image URL as first argument.

If a File or Blob is passed as parameter, it returns an HTML img element if the browser supports the URL API, alternatively a FileReader object if the FileReader API is supported, or false.

It always returns an HTML img element when passing an image URL:

var loadingImage = loadImage(
  'https://example.org/image.png',
  function (img) {
    document.body.appendChild(img)
  },
  { maxWidth: 600 }
)

Cancel image loading

Some browsers (e.g. Chrome) will cancel the image loading process if the src property of an img element is changed.
To avoid unnecessary requests, we can use the data URL of a 1x1 pixel transparent GIF image as src target to cancel the original image download.

To disable callback handling, we can also unset the image event handlers and for maximum browser compatibility, cancel the file reading process if the returned object is a FileReader instance:

var loadingImage = loadImage(
  'https://example.org/image.png',
  function (img) {
    document.body.appendChild(img)
  },
  { maxWidth: 600 }
)

if (loadingImage) {
  // Unset event handling for the loading image:
  loadingImage.onload = loadingImage.onerror = null

  // Cancel image loading process:
  if (loadingImage.abort) {
    // FileReader instance, stop the file reading process:
    loadingImage.abort()
  } else {
    // HTMLImageElement element, cancel the original image request by changing
    // the target source to the data URL of a 1x1 pixel transparent image GIF:
    loadingImage.src =
      'data:image/gif;base64,' +
      'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
  }
}

Please note:
The img element (or FileReader instance) for the loading image is only returned when using the callback style API and not available with the Promise based API.

Callback arguments

For the callback style API, the second argument to loadImage() must be a callback function, which is called when the image has been loaded or an error occurred while loading the image.

The callback function is passed two arguments:

  1. An HTML img element or canvas element, or an Event object of type error.
  2. An object with the original image dimensions as properties and potentially additional metadata.
loadImage(
  fileOrBlobOrUrl,
  function (img, data) {
    document.body.appendChild(img)
    console.log('Original image width: ', data.originalWidth)
    console.log('Original image height: ', data.originalHeight)
  },
  { maxWidth: 600, meta: true }
)

Please note:
The original image dimensions reflect the natural width and height of the loaded image before applying any transformation.
For consistent values across browsers, metadata parsing has to be enabled via meta:true, so loadImage can detect automatic image orientation and normalize the dimensions.

Error handling

Example code implementing error handling:

loadImage(
  fileOrBlobOrUrl,
  function (img, data) {
    if (img.type === 'error') {
      console.error('Error loading image file')
    } else {
      document.body.appendChild(img)
    }
  },
  { maxWidth: 600 }
)

Promise

If the loadImage() function is called without a callback function as second argument and the Promise API is available, it returns a Promise object:

loadImage(fileOrBlobOrUrl, { maxWidth: 600, meta: true })
  .then(function (data) {
    document.body.appendChild(data.image)
    console.log('Original image width: ', data.originalWidth)
    console.log('Original image height: ', data.originalHeight)
  })
  .catch(function (err) {
    // Handling image loading errors
    console.log(err)
  })

The Promise resolves with an object with the following properties:

  • image: An HTML img or canvas element.
  • originalWidth: The original width of the image.
  • originalHeight: The original height of the image.

Please also read the note about original image dimensions normalization in the callback arguments section.

If metadata has been parsed, additional properties might be present on the object.

If image loading fails, the Promise rejects with an Event object of type error.

Options

The optional options argument to loadImage() allows to configure the image loading.

It can be used the following way with the callback style:

loadImage(
  fileOrBlobOrUrl,
  function (img) {
    document.body.appendChild(img)
  },
  {
    maxWidth: 600,
    maxHeight: 300,
    minWidth: 100,
    minHeight: 50,
    canvas: true
  }
)

Or the following way with the Promise based API:

loadImage(fileOrBlobOrUrl, {
  maxWidth: 600,
  maxHeight: 300,
  minWidth: 100,
  minHeight: 50,
  canvas: true
}).then(function (data) {
  document.body.appendChild(data.image)
})

All settings are optional. By default, the image is returned as HTML img element without any image size restrictions.

maxWidth

Defines the maximum width of the img/canvas element.

maxHeight

Defines the maximum height of the img/canvas element.

minWidth

Defines the minimum width of the img/canvas element.

minHeight

Defines the minimum height of the img/canvas element.

sourceWidth

The width of the sub-rectangle of the source image to draw into the destination canvas.
Defaults to the source image width and requires canvas: true.

sourceHeight

The height of the sub-rectangle of the source image to draw into the destination canvas.
Defaults to the source image height and requires canvas: true.

top

The top margin of the sub-rectangle of the source image.
Defaults to 0 and requires canvas: true.

right

The right margin of the sub-rectangle of the source image.
Defaults to 0 and requires canvas: true.

bottom

The bottom margin of the sub-rectangle of the source image.
Defaults to 0 and requires canvas: true.

left

The left margin of the sub-rectangle of the source image.
Defaults to 0 and requires canvas: true.

contain

Scales the image up/down to contain it in the max dimensions if set to true.
This emulates the CSS feature background-image: contain.

cover

Scales the image up/down to cover the max dimensions with the image dimensions if set to true.
This emulates the CSS feature background-image: cover.

aspectRatio

Crops the image to the given aspect ratio (e.g. 16/9).
Setting the aspectRatio also enables the crop option.

pixelRatio

Defines the ratio of the canvas pixels to the physical image pixels on the screen.
Should be set to window.devicePixelRatio unless the scaled image is not rendered on screen.
Defaults to 1 and requires canvas: true.

downsamplingRatio

Defines the ratio in which the image is downsampled (scaled down in steps).
By default, images are downsampled in one step.
With a ratio of 0.5, each step scales the image to half the size, before reaching the target dimensions.
Requires canvas: true.

imageSmoothingEnabled

If set to false, disables image smoothing.
Defaults to true and requires canvas: true.

imageSmoothingQuality

Sets the quality of image smoothing.
Possible values: 'low', 'medium', 'high'
Defaults to 'low' and requires canvas: true.

crop

Crops the image to the maxWidth/maxHeight constraints if set to true.
Enabling the crop option also enables the canvas option.

orientation

Transform the canvas according to the specified Exif orientation, which can be an integer in the range of 1 to 8 or the boolean value true.

When set to true, it will set the orientation value based on the Exif data of the image, which will be parsed automatically if the Exif extension is available.

Exif orientation values to correctly display the letter F:

    1             2
  โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ        โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ
  โ–ˆโ–ˆ                โ–ˆโ–ˆ
  โ–ˆโ–ˆโ–ˆโ–ˆ            โ–ˆโ–ˆโ–ˆโ–ˆ
  โ–ˆโ–ˆ                โ–ˆโ–ˆ
  โ–ˆโ–ˆ                โ–ˆโ–ˆ

    3             4
      โ–ˆโ–ˆ        โ–ˆโ–ˆ
      โ–ˆโ–ˆ        โ–ˆโ–ˆ
    โ–ˆโ–ˆโ–ˆโ–ˆ        โ–ˆโ–ˆโ–ˆโ–ˆ
      โ–ˆโ–ˆ        โ–ˆโ–ˆ
  โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ        โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ

    5             6
โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ    โ–ˆโ–ˆ
โ–ˆโ–ˆ  โ–ˆโ–ˆ        โ–ˆโ–ˆ  โ–ˆโ–ˆ
โ–ˆโ–ˆ            โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ

    7             8
        โ–ˆโ–ˆ    โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ
    โ–ˆโ–ˆ  โ–ˆโ–ˆ        โ–ˆโ–ˆ  โ–ˆโ–ˆ
โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ            โ–ˆโ–ˆ

Setting orientation to true enables the canvas and meta options, unless the browser supports automatic image orientation (see browser support for image-orientation).

Setting orientation to 1 enables the canvas and meta options if the browser does support automatic image orientation (to allow reset of the orientation).

Setting orientation to an integer in the range of 2 to 8 always enables the canvas option and also enables the meta option if the browser supports automatic image orientation (again to allow reset).

meta

Automatically parses the image metadata if set to true.

If metadata has been found, the data object passed as second argument to the callback function has additional properties (see metadata parsing).

If the file is given as URL and the browser supports the fetch API or the XHR responseType blob, fetches the file as Blob to be able to parse the metadata.

canvas

Returns the image as canvas element if set to true.

crossOrigin

Sets the crossOrigin property on the img element for loading CORS enabled images.

noRevoke

By default, the created object URL is revoked after the image has been loaded, except when this option is set to true.

Metadata parsing

If the Load Image Meta extension is included, it is possible to parse image meta data automatically with the meta option:

loadImage(
  fileOrBlobOrUrl,
  function (img, data) {
    console.log('Original image head: ', data.imageHead)
    console.log('Exif data: ', data.exif) // requires exif extension
    console.log('IPTC data: ', data.iptc) // requires iptc extension
  },
  { meta: true }
)

Or alternatively via loadImage.parseMetaData, which can be used with an available File or Blob object as first argument:

loadImage.parseMetaData(
  fileOrBlob,
  function (data) {
    console.log('Original image head: ', data.imageHead)
    console.log('Exif data: ', data.exif) // requires exif extension
    console.log('IPTC data: ', data.iptc) // requires iptc extension
  },
  {
    maxMetaDataSize: 262144
  }
)

Or using the Promise based API:

loadImage
  .parseMetaData(fileOrBlob, {
    maxMetaDataSize: 262144
  })
  .then(function (data) {
    console.log('Original image head: ', data.imageHead)
    console.log('Exif data: ', data.exif) // requires exif extension
    console.log('IPTC data: ', data.iptc) // requires iptc extension
  })

The Metadata extension adds additional options used for the parseMetaData method:

  • maxMetaDataSize: Maximum number of bytes of metadata to parse.
  • disableImageHead: Disable parsing the original image head.
  • disableMetaDataParsers: Disable parsing metadata (image head only)

Image head

Resized JPEG images can be combined with their original image head via loadImage.replaceHead, which requires the resized image as Blob object as first argument and an ArrayBuffer image head as second argument.

With callback style, the third argument must be a callback function, which is called with the new Blob object:

loadImage(
  fileOrBlobOrUrl,
  function (img, data) {
    if (data.imageHead) {
      img.toBlob(function (blob) {
        loadImage.replaceHead(blob, data.imageHead, function (newBlob) {
          // do something with the new Blob object
        })
      }, 'image/jpeg')
    }
  },
  { meta: true, canvas: true, maxWidth: 800 }
)

Or using the Promise based API like this:

loadImage(fileOrBlobOrUrl, { meta: true, canvas: true, maxWidth: 800 })
  .then(function (data) {
    if (!data.imageHead) throw new Error('Could not parse image metadata')
    return new Promise(function (resolve) {
      data.image.toBlob(function (blob) {
        data.blob = blob
        resolve(data)
      }, 'image/jpeg')
    })
  })
  .then(function (data) {
    return loadImage.replaceHead(data.blob, data.imageHead)
  })
  .then(function (blob) {
    // do something with the new Blob object
  })
  .catch(function (err) {
    console.error(err)
  })

Please note:
Blob objects of resized images can be created via HTMLCanvasElement.toBlob.
blueimp-canvas-to-blob provides a polyfill for browsers without native canvas.toBlob() support.

Exif parser

If you include the Load Image Exif Parser extension, the argument passed to the callback for parseMetaData will contain the following additional properties if Exif data could be found in the given image:

  • exif: The parsed Exif tags
  • exifOffsets: The parsed Exif tag offsets
  • exifTiffOffset: TIFF header offset (used for offset pointers)
  • exifLittleEndian: little endian order if true, big endian if false

The exif object stores the parsed Exif tags:

var orientation = data.exif[0x0112] // Orientation

The exif and exifOffsets objects also provide a get() method to retrieve the tag value/offset via the tag's mapped name:

var orientation = data.exif.get('Orientation')
var orientationOffset = data.exifOffsets.get('Orientation')

By default, only the following names are mapped:

If you also include the Load Image Exif Map library, additional tag mappings become available, as well as three additional methods:

  • exif.getText()
  • exif.getName()
  • exif.getAll()
var orientationText = data.exif.getText('Orientation') // e.g. "Rotate 90ยฐ CW"

var name = data.exif.getName(0x0112) // "Orientation"

// A map of all parsed tags with their mapped names/text as keys/values:
var allTags = data.exif.getAll()

Exif Thumbnail

Example code displaying a thumbnail image embedded into the Exif metadata:

loadImage(
  fileOrBlobOrUrl,
  function (img, data) {
    var exif = data.exif
    var thumbnail = exif && exif.get('Thumbnail')
    var blob = thumbnail && thumbnail.get('Blob')
    if (blob) {
      loadImage(
        blob,
        function (thumbImage) {
          document.body.appendChild(thumbImage)
        },
        { orientation: exif.get('Orientation') }
      )
    }
  },
  { meta: true }
)

Exif IFD

Example code displaying data from the Exif IFD (Image File Directory) that contains Exif specified TIFF tags:

loadImage(
  fileOrBlobOrUrl,
  function (img, data) {
    var exifIFD = data.exif && data.exif.get('Exif')
    if (exifIFD) {
      // Map of all Exif IFD tags with their mapped names/text as keys/values:
      console.log(exifIFD.getAll())
      // A specific Exif IFD tag value:
      console.log(exifIFD.get('UserComment'))
    }
  },
  { meta: true }
)

GPSInfo IFD

Example code displaying data from the Exif IFD (Image File Directory) that contains GPS info:

loadImage(
  fileOrBlobOrUrl,
  function (img, data) {
    var gpsInfo = data.exif && data.exif.get('GPSInfo')
    if (gpsInfo) {
      // Map of all GPSInfo tags with their mapped names/text as keys/values:
      console.log(gpsInfo.getAll())
      // A specific GPSInfo tag value:
      console.log(gpsInfo.get('GPSLatitude'))
    }
  },
  { meta: true }
)

Interoperability IFD

Example code displaying data from the Exif IFD (Image File Directory) that contains Interoperability data:

loadImage(
  fileOrBlobOrUrl,
  function (img, data) {
    var interoperabilityData = data.exif && data.exif.get('Interoperability')
    if (interoperabilityData) {
      // The InteroperabilityIndex tag value:
      console.log(interoperabilityData.get('InteroperabilityIndex'))
    }
  },
  { meta: true }
)

Exif parser options

The Exif parser adds additional options:

  • disableExif: Disables Exif parsing when true.
  • disableExifOffsets: Disables storing Exif tag offsets when true.
  • includeExifTags: A map of Exif tags to include for parsing (includes all but the excluded tags by default).
  • excludeExifTags: A map of Exif tags to exclude from parsing (defaults to exclude Exif MakerNote).

An example parsing only Orientation, Thumbnail and ExifVersion tags:

loadImage.parseMetaData(
  fileOrBlob,
  function (data) {
    console.log('Exif data: ', data.exif)
  },
  {
    includeExifTags: {
      0x0112: true, // Orientation
      ifd1: {
        0x0201: true, // JPEGInterchangeFormat (Thumbnail data offset)
        0x0202: true // JPEGInterchangeFormatLength (Thumbnail data length)
      },
      0x8769: {
        // ExifIFDPointer
        0x9000: true // ExifVersion
      }
    }
  }
)

An example excluding Exif MakerNote and GPSInfo:

loadImage.parseMetaData(
  fileOrBlob,
  function (data) {
    console.log('Exif data: ', data.exif)
  },
  {
    excludeExifTags: {
      0x8769: {
        // ExifIFDPointer
        0x927c: true // MakerNote
      },
      0x8825: true // GPSInfoIFDPointer
    }
  }
)

Exif writer

The Exif parser extension also includes a minimal writer that allows to override the Exif Orientation value in the parsed imageHead ArrayBuffer:

loadImage(
  fileOrBlobOrUrl,
  function (img, data) {
    if (data.imageHead && data.exif) {
      // Reset Exif Orientation data:
      loadImage.writeExifData(data.imageHead, data, 'Orientation', 1)
      img.toBlob(function (blob) {
        loadImage.replaceHead(blob, data.imageHead, function (newBlob) {
          // do something with newBlob
        })
      }, 'image/jpeg')
    }
  },
  { meta: true, orientation: true, canvas: true, maxWidth: 800 }
)

Please note:
The Exif writer relies on the Exif tag offsets being available as data.exifOffsets property, which requires that Exif data has been parsed from the image.
The Exif writer can only change existing values, not add new tags, e.g. it cannot add an Exif Orientation tag for an image that does not have one.

IPTC parser

If you include the Load Image IPTC Parser extension, the argument passed to the callback for parseMetaData will contain the following additional properties if IPTC data could be found in the given image:

  • iptc: The parsed IPTC tags
  • iptcOffsets: The parsed IPTC tag offsets

The iptc object stores the parsed IPTC tags:

var objectname = data.iptc[5]

The iptc and iptcOffsets objects also provide a get() method to retrieve the tag value/offset via the tag's mapped name:

var objectname = data.iptc.get('ObjectName')

By default, only the following names are mapped:

  • ObjectName

If you also include the Load Image IPTC Map library, additional tag mappings become available, as well as three additional methods:

  • iptc.getText()
  • iptc.getName()
  • iptc.getAll()
var keywords = data.iptc.getText('Keywords') // e.g.: ['Weather','Sky']

var name = data.iptc.getName(5) // ObjectName

// A map of all parsed tags with their mapped names/text as keys/values:
var allTags = data.iptc.getAll()

IPTC parser options

The IPTC parser adds additional options:

  • disableIptc: Disables IPTC parsing when true.
  • disableIptcOffsets: Disables storing IPTC tag offsets when true.
  • includeIptcTags: A map of IPTC tags to include for parsing (includes all but the excluded tags by default).
  • excludeIptcTags: A map of IPTC tags to exclude from parsing (defaults to exclude ObjectPreviewData).

An example parsing only the ObjectName tag:

loadImage.parseMetaData(
  fileOrBlob,
  function (data) {
    console.log('IPTC data: ', data.iptc)
  },
  {
    includeIptcTags: {
      5: true // ObjectName
    }
  }
)

An example excluding ApplicationRecordVersion and ObjectPreviewData:

loadImage.parseMetaData(
  fileOrBlob,
  function (data) {
    console.log('IPTC data: ', data.iptc)
  },
  {
    excludeIptcTags: {
      0: true, // ApplicationRecordVersion
      202: true // ObjectPreviewData
    }
  }
)

License

The JavaScript Load Image library is released under the MIT license.

Credits

  • Original image metadata handling implemented with the help and contribution of Achim Stรถhr.
  • Original Exif tags mapping based on Jacob Seidelin's exif-js library.
  • Original IPTC parser implementation by Dave Bevan.

javascript-load-image's People

Contributors

andyogo avatar bevand10 avatar blueimp avatar bubbatls avatar fleg avatar gre avatar igorbernstein avatar jjwon0 avatar joewood avatar micky2be avatar naoina avatar nateowami avatar phoenix303 avatar poshaughnessy avatar redgeoff avatar royhaddad avatar ruscoder avatar ruudt avatar studiomax avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

javascript-load-image's Issues

Hiding result <div> doesn't allow the same image to be selected back to back

I modified the demo script because I was seeing a problem in my own code and wanted to make sure it wasn't something else in my code. I am basically hiding the result

with a "restart" button in the actions section. So the flow to reproduce the issue is as follows.

  1. browse for an image
  2. after it displays, click the restart button to hide the result
  3. click choose file again and select the same image
  4. notice the result
    is still hidden.

Here are the only changes I made that replicates this.

  • added restart button to actions and added on click handler that hides result

    restart

    $('#restart').on('click', function (event)
    {
    result.hide();
    });

  • added display: none; to .result selector in demo.css

  • added result.show(); in replaceResults() below the replaceWith() call

documentation suggestion for 'orientation'

First fantastic library, thank you very much.

My suggestion: the documentation for the option 'orientation' isn't clear to me. I burned time thinking that it was supposed to be a boolean (i.e. "do the orientation transform"), when in fact, it should be the exif orientation number that you want it to transform. I learned that by looking at the demo source code.

To fix this, perhaps say "The EXIF orientation value to transform the canvas coordinates. Default is null, which means no transform."

thanks!
jeff

Resizing as blob?

I have a blob. I don't know if it's a jpg or a png. I wish to resize and crop it and keep it as a blob. Is there any easy way to this with this lib?

using with jcrop not working

I have the following code, when jcrop initializes the image goes blank, appreciate any help you can provide

document.getElementById('strImage').onchange = function (e) {
boxW = Math.round($(window).width()-35);
boxH = Math.round($(window).height()-150);
var oImage = $(".egImgPreviewContainer");

                    var loadingImage = loadImage(
                        e.target.files[0],
                        function (img) {

                            oImage.html(img);
                            $('.egImgPreviewContainer > img').attr('id','egUploadPreview');

                            orgAspectRatio = img.width/img.height;
                            cropX = 10;
                            cropY = 10;
                            cropX2 = (img.width-100)*orgAspectRatio;
                            cropY2 = (img.height-100)*orgAspectRatio;

                            //show upload buton
                            $(".egBtnUpload").show();

                            /*
                            setTimeout(function(){
                                // initialize Jcrop
                                $("#egUploadPreview").Jcrop({
                                    //minSize: [32, 32], // min crop size
                                    aspectRatio :orgAspectRatio, // keep aspect ratio 1:1
                                    bgFade: true, // use fade effect
                                    bgOpacity: .5, // fade opacity
                                    onChange: egUpdateImageInfo,
                                    onSelect: egUpdateImageInfo,
                                    allowSelect:false,
                                    setSelect:[cropX,cropY,cropX2,cropY2],
                                    allowResize:false
                                    }, function()
                                        {
                                            // use the Jcrop API to get the real image size
                                            var bounds = this.getBounds();
                                            boundx = bounds[0];
                                            boundy = bounds[1];                 

                                            $("#oW").val(boundx);
                                            $("#oH").val(boundy);                   

                                            // Store the Jcrop API in the jcrop_api variable
                                            jcrop_api = this;

                                            //show upload buton
                                            $(".egBtnUpload").show();

                                        });
                            },3000);    
                            */              
                            //alertify.log(img.width + 'x' + img.height);
                        },
                        {
                            maxWidth: boxW,
                            maxHeight:boxH,
                            canvas:false
                        }
                );



            };

please update to latest

JavaScript-Load-Image / js / load-image.js

Minified version seems to be newer than this version. Switching to unminified triggers errors.

Trouble with load-image-ios.js

Either I am using this lib wrong, or there is an actual problem.

There's no stretching on other apple devices (various iPads, iPhone4), but on the iPhone5 images are always squashed.

IE 10 fails on very specific images - example attached

This very well may be a bug or extra security restriction in IE 10 but I have found two images that refuse to work with your demo.

I noticed the problem when developing functionality almost identical to yours for my app.

IE would always fail to read this specific image. I came across your plugin when searching for a solution and low and behold, your plugin has the same issue.

From what I can ascertain the blob URL is created correctly with createObjectURL as the returned URL appears as any other correctly loading image.

However the image.onload event never fires for it and it is never actually loaded into the browser. I cannot for the life of me figure out why and what is different about this image to the other 99% of images out there.

It CAN be read by the filereader interface, so a possible solution would be to set an error timeout which will run if the image.onload event has not fired after say 5-6 seconds and restarts the read using the filereader API to create a base64 image instead of a blob URL reference.

It's ugly and hacky would be a temporary fix until we can work out just whats going on.

I have attached one of the images in question.

1920x1080-desktop-wallpaper-high-resolution-171614870

suggestion when uploading an image

awesome code. really.
I know my suggestion isn't the idea of the code, but it would be nice to add some sort of client-side image resizing option, to save the server the trouble prior to uploading, and also make it quicker. I know of other scripts out there which does that, but it would be good to integrate it with your IMHO.

you might know this project, but it's nice: http://www.plupload.com/
another read: https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader

Allow sourceX, sourceY, destX, and destY to be passed in as options

It would be nice to have control over the crop position. The variables mentioned in the title are currently set to zero (near line 167). A quick and dirty fix would be to replace these 4 lines with the following:

sourceX = options.sourceX ? options.sourceX : 0,
sourceY = options.sourceY ? options.sourceY : 0,
destX = options.destX ? options.destX : 0,
destY = options.destY ? options.destY : 0,

Low quality of scaled image with canvas: true

Hey,

with canvas: true the quality of scaled images is significantly lower:

diff
On the left is the result with canvas: false, and on the right is result with canvas: true.
This is result from Chrome, in Firefox it looks the same. I haven't tried IE.

This is the original image:

1

No GPS Lat/Long after resized image on IOS

I use loadImage.parseMetaData to combine imageHead to resizedImage and then I got a new image with meta data include GPS Lat/Long. Unfortunately it works fine only on android but ios not works.
Anyone know how to fix this?

Thanks !

Add decimal output of GPS coordinates

Oftentimes you want GPS coordinates in decimal format rather than the format given in the EXIF data. This can come in handy if you're trying to pinpoint an image's GPS location on a map using the Google Maps API. It would be nice if this conversion could be done inside of JavaScript Load Image. Here's the code I'm currently using to make this conversion:

function(GPSLatitude, GPSLatitudeRef, GPSLongitude, GPSLongitudeRef) {
  var coordinates = [];
  var location = [];
  location.push({coordinate: GPSLatitude, hemisphere: GPSLatitudeRef});
  location.push({coordinate: GPSLongitude, hemisphere: GPSLongitudeRef});
  for (var i = 0; i < 2; i++) {
    var degrees = location[i].coordinate[0];
    var minutes = location[i].coordinate[1];
    var seconds = location[i].coordinate[2];
    var sign = location[i].hemisphere == "W" || location[i].hemisphere == "S" ? -1 : 1;
    coordinates.push(sign * (degrees + minutes/60 + seconds/3600));
  }
  return coordinates;
}

Drawing scaled images to canvas fails on iOS devices for large image sizes

StackOverflow references:

HTML5 Canvas drawImage ratio bug iOS
MobileSafari not returning the right image size info via JavaScript
Mobile Safari renders scaled on Canvas?

iOS references:

Known iOS Resource Limits

Possible solution:

There is a JavaScript canvas resize library which works around the subsampling and vertical squash issues encountered when drawing scaled images on canvas on iOS devices: http://github.com/stomita/ios-imagefile-megapixel

There are side issues when scaling images with alpha channel (as it uses the alpha channel for the issues detection) and when trying to resize existing canvas elements.
However, it does solve the issue at hand.

Restricting only the smaller dimension when resizing

This is a great plugin! I have a suggestion that might make it even more useful.

I often need to resize an image while restricting only the smaller of the two dimensions, similar to the behavior of background-size: cover in CSS. Since you don't necessarily know whether the image is portrait or landscape, you can't simply use the maxWidth or maxHeight options to accomplish this. This would require a new option that would look something like this:

smallDimension: 500

In this case, if the image is portrait, the width would be constrained to 500 pixels. If the image is landscape, the height would be constrained to 500 pixels.

I can not connect

Thank you for the great plugin.
How to connect, download the images to thejQuery Multiple File Upload Plugin?
I got only the display output to one point and then does not go

$(function(){ // wait for document to load 
   $('#input-file').MultiFile({ 
  list: '#list',
  STRING: {
    file: '<span id="result"></span><span title="Click to remove" onclick="$(this).parent().prev().click()">$file</span>',
    remove: '<img src="/i/bin.gif" height="16" width="16" alt="x"/>',
   },
 });
 document.getElementById('input-file').onchange = function (e) {
    window.loadImage(
        e.target.files[0],
        function (img) {
             $("#result").append(img);
        },
        {maxWidth: 100}
    )
};

});

html:

<form action="">
<input type="file" id="input-file"/>
</form>
<div id="list"></div>

canvas.toJSON()

Hi!
I really like your plugin.
But I'm missing one specific feature. It would be great to do something like
canvas.toJSON() to be able to store the cropped/scaled images into database.

Best
Albert

JavaScript-Load-Image problem with requirejs

I found there is problem with your load-image plugin when loaded with requirejs

<script>
var require = {
    baseUrl: 'js',
    paths: {
        "jquery"     :['jquery-1.11.0.min'],
        'load-image' :['http://blueimp.github.io/JavaScript-Load-Image/js/load-image.min'],
    },
    shim:{
        'load-image' :['jquery'],
    }
}
</script>
<script src="require.min.js"></script>
<script type="text/javascript">
function loadimage(){
require([ 'load-image'],function(){
            console.log("load-image loaded");
        });
};
function loadjquery(){
require([ 'jquery'],function(){
            console.log("jquery loaded");
        });
};
</script>

When I run loadimage function for the first time, everything seems fine. But after that, if I try to run loadimage function again or loadjquery function, or just any code that will run requirejs, I will get this error:

Error message from Firebug (require.min.js on line 8):

Error: Mismatched anonymous define() module: function (a){"use strict";var b=a.hasCanvasOption;a.hasCanvasOption=function(a){return b(a)||a.orientation},a.transformCoordinates=function(a,b){var c=a.getContext("2d"),d=a.width,e=a.height,f=b.orientation;if(f)switch(f>4&&(a.width=e,a.height=d),f){case 2:c.translate(d,0),c.scale(-1,1);break;case 3:c.translate(d,e),c.rotate(Math.PI);break;case 4:c.translate(0,e),c.scale(1,-1);break;case 5:c.rotate(.5*Math.PI),c.scale(1,-1);break;case 6:c.rotate(.5*Math.PI),c.translate(0,-e);break;case 7:c.rotate(.5*Math.PI),c.translate(d,-e),c.scale(-1,1);break;case 8:c.rotate(-.5*Math.PI),c.translate(-d,0)}},a.getTransformedOptions=function(a){if(!a.orientation||1===a.orientation)return a;var b,c={};for(b in a)a.hasOwnProperty(b)&&(c[b]=a[b]);switch(a.orientation){case 2:c.left=a.right,c.right=a.left;break;case 3:c.left=a.right,c.top=a.bottom,c.right=a.left,c.bottom=a.top;break;case 4:c.top=a.bottom,c.bottom=a.top;break;case 5:c.left=a.top,c.top=a.left,c.right=a.bottom,c.bottom=a.right;break;case 6:c.left=a.top,c.top=a.right,c.right=a.bottom,c.bottom=a.left;break;case 7:c.left=a.bottom,c.top=a.right,c.right=a.top,c.bottom=a.left;break;case 8:c.left=a.bottom,c.top=a.left,c.right=a.top,c.bottom=a.right}return a.orientation>4&&(c.maxWidth=a.maxHeight,c.maxHeight=a.maxWidth,c.minWidth=a.minHeight,c.minHeight=a.minWidth,c.sourceWidth=a.sourceHeight,c.sourceHeight=a.sourceWidth),c}} http://requirejs.org/docs/errors.html#mismatch

Hope the problem can get fixed soon. Or you have any suggestion to get it works?

Thank you.

Multiple file

Hi,
I set the input file as "multiple" and I wish I would create an image for each file.
For now I have done so and it works, but it returns an error that I did not understand what it is and I would like to delete it:

document.getElementById('multimedia_file').onchange = function (e) {
                for (var key in e.target.files){ 
                window.loadImage(
                    e.target.files[key],
                function (img) {
                    $('#drop').append(img);
                },
                {maxWidth: 100, maxHeight: 100, canvas: true}
                );
                };

            };

This is the error:

GET http://localhost/MyBusiness0_1/web/app_dev.php/114/function%20item()%20%7B%20[native%20code]%20%7D 404 (Not Found)                                             load-image.min.js:1

Is there a better way to do what I need?

Add a Upload Example

Hi there, nice project !

It would be cool to see how you would do an Upload after the cropping in the demo.

Cheers !

loadImage does not work for ios if canvas option is set to true

Hi Sebastian:

I'm not sure is it a good way to describe the problem.

The test demo is fairly simple, you can access it via:
http://canvas-load-image-test.s3-website-us-east-1.amazonaws.com/

If canvas option is set to true, loadImage function won't work for my iPhone 4S. I've tried the demo in desktop browser and Nexus, it works fine for those devices.

However, if we set canvas to false and then resize the image using {canvas: true}, it will work, just like the preview feature you used in:
http://blueimp.github.io/jQuery-File-Upload/

I also find that for iPhone 4s, the test demo works for images from screenshot (does not work for images from camera), so I guess the problem has something to do with processing exif data in ios.

Thanks,
Sidney

Using load image in wordpress

I really want to praise you for creating such a cool yet simple code.
I am having a problem using it in wordpress template. I am creating a wordpress template on bootstrap and trying to embed your javascript in my gallery section. The images load fine on the main window. But when I click on the image to initiate the modal view, it opens image in the browser window. When I click on the start slidshow button it open a modal view but without image. i am defining my css and javascript in the function file.

// Loading All CSS Stylesheets

function themebootstrap_css_loader() {
wp_enqueue_style('style', get_template_directory_uri().'/css/bootstrap.min.css', false ,'1.1', 'all' );
wp_enqueue_style('style', get_template_directory_uri().'/css/bootstrap-image-gallery.min.css', false ,'1.1', 'all' );
}
add_action('wp_enqueue_scripts', 'themebootstrap_css_loader');

// Loading all JS Script Files. Remove any files you are not using!

function themebootstrap_js_loader() {
wp_enqueue_script('application', get_template_directory_uri().'/js/bootstrap.min.js', array('tooltip'),'1.0', true );
wp_enqueue_script('application', get_template_directory_uri().'/js/bootstrap-image-gallery.min.js', array('tooltip'),'1.0', true );
wp_enqueue_script('application', get_template_directory_uri().'/js/load-load-image.js', array('tooltip'),'1.0', true );
wp_enqueue_script('application', get_template_directory_uri().'/js/load-image.min.js', array('tooltip'),'1.0', true );

}
add_action('wp_enqueue_scripts', 'themebootstrap_js_loader');

I tried to declare it in the template page but of no use. Please advice me and help me in soughting out this problem

Regards

Deepak

issue with requirejs and the minified version of load-image

I set up a fairly simple file upload page using fileupload-ui and one other jquery plugin. Initially I used the minified versions of all the dependencies. Everything was set up in RequireJS and the rest of the site works as expected. When visiting the page with the jquery.fileupload plugin I would get random "undefined" type of errors. Sometimes the page would load fine, but mostly there would be something missing and it was always different.

At that point I swapped out minified versions so I could start breaking down where the breakage in dependencies was. Suddenly everything worked. I then narrowed it down to load-image.js.

Unfortunately I don't have exact prof as to why the minified version behaves differently, or if it's coincidence in timing but I figured I'd let you know I had an issue.

I was working with the files in master.

loadImage firing callback multiple times in Firefox

I am using Firefox 22.0 and I am noticing that loadImage callback is firing multiple times causing issues. This does not happen in Chrome.

Am I doing something wrong?

I am just calling, load image inside a drop handler
if (!loadImage(
imageFile,
that._loadImageSuccess
)) {
//TODO: Handle failure case
}

Thanks a lot!
Vishal

Option to define crop ratio

Would be great to be able to define width/height ratio for cropping. Useful when required to crop squares.

parseMetaData + loadImage in a loop

I'm trying to iterate the files object including the orientation option of each image. My goal is to do an each for the files object and then be able to load each image with its fixed orientation (options orientation)

This is my code:

var _options = {
        maxWidth: 200,
        minWidth: 200
    };
$.each(files, function(i){
    var file = files[i];
    loadImage.parseMetaData(file, function(data){
        _options.orientation = "";
        if(data.exif) _options.orientation = data.exif.get("Orientation");
        console.log(_options);
        loadImage(file, function(img){
            console.log(_options);
        }, _options);
    });
});

Thing is that _options in loadImage are always those that where taken from the last image. Problem is that I can't parse the correct option values to fix the image orientation in this loop because it seems that loadImage runs async

How should I iterate this to make the _options work for the correct image every time? There is a workaround or should I fire the next iteration inside loadImage (something like issue loadImage for files[0] and once is done run a callback to load files[i])

Thanks.

Multiple instances of Error message

When non blob files are uploaded, an error message is displayed. When this is done multiple times, the display shows multiple error messages. Attached is the screenshot of the error in Firefox.

  1. First attempt to upload non blob file
    first

  2. Second attempt to upload non blob file
    second

  3. Third attempt to upload non blob file
    third

subtle bug

There is a subtle bug that I'm running into here
https://github.com/blueimp/JavaScript-Load-Image/blob/master/load-image.js#L73

When i img.width is set it seems img.height is set as well (to something proportional) so that when it goes to execute the next line, it does the calculation with the already properly calculated height and it makes it way too short.

I only run into this situation when I run loadImage() twice on different items, I wish I had time to debug further, but for now I can fix this by assigning the height and width to temporary variables then assigning them at once.

just wanted to let you know.
Browser is Chrome 19 but it also happens in FF 10.

keep aspect ratio

Hi,

anyway to keep the aspect ration when resizing an image?

My main problem is that any time a user uses a portrait pictures it gets resized and stretched to landscape.

load image + hidden input + file browser not working

I tried to integrate your script in a small project of mine.
I am using a online file browser (PDW File Browser) and a hidden input field.
I can see value of the hidden field is changed when i select another image (with the URL of the image file).
However... the file will not show using your script.

When i change the input type to "file" and select an image from my pc it works flawless.

Not really sure if there is anything i am doing wrong or if it is a limitation in the script?

Upload Problem to this specific photo

Hi,

Ive been trying to upload the attached image it seems there is white gap space in the bottom part of the image. Ive try other image but they seems to be ok.

I used the plugins in my web app and its work fine except for the attach photo. And i also noticed that that there is part of the photo is missing after uploading.

Here is the screen shot
whitespace

Sample Photo:
013

Just want to ask what is the reason why is it happen in this particular image.

Thanks in advance

Browser Compatibility Question

I know that the docs say that this only supports browser that support the File api. Did this library ever support IE8/9 and if so what version did that change. Thanks

Question about mem usage

Hey there, if you use the FileReader on very large files, it creates a base64 encoded string which might impact browser performance. Is this also true with the load image? And if so, wouldn't it be possible to discard of that 'large' base64 string if you use the canvas to blob library you also wrote? Might be a cool feature. Please give me your thoughts.

Failed to load resources

Everything was working fine until yesterday.
From looking on github I see various file updates from yesterday to the blueimp project (and maybe something has stopped my instance of this install working).

I'm getting the following errors:
Failed to load resource: the server responded with a status of 404 (Not Found)http://blueimp.github.io/JavaScript-Templates/tmpl.min.js

Failed to load resource: the server responded with a status of 404 (Not Found)http://blueimp.github.io/JavaScript-Load-Image/load-image.min.js

Failed to load resource: the server responded with a status of 404 (Not Found)http://blueimp.github.io/JavaScript-Canvas-to-Blob/canvas-to-blob.min.js

crossOrigin

Remote images to blob securty error:

img.crossOrigin = "Anonymous";

Does not work in IE and webkit?

Very good plugin, congratulations!
I tested the plugin in all browsers demo page, but in IE and Safari browsers does not work.

IE has error demo page
Message: Can not get property value '0 ': the object is null or not defined
Line: 97
Character: 13
Code: 0
URI: http:// blueimp.github.com/JavaScript-Load-Image/

Safari does not work

loadImage.renderImageToCanvas doesn't convert sourceX and sourceY for orientation

I'm trying to adapt the plugin to allow custom cropping, so I've been pairing this with the jWindowCrop plugin in order to pick a crop position, and then passing the result along to a customized loadImage.scale function that supports handling sourceX and sourceY. The current version assumes they're always 0, which means when cropping to square it crops along the bottom of my photos instead of the center which is a really strange default behavior.

Anyway, for the most part things are working well, except when it comes to images of different orientations. By default, my coordinates work great. With orientation 6, I swap the sourceX and sourceY and it's fine. However beyond that I'm in trouble. In orientation 3, for example, I see in loadImage.renderImageToCanvas that it has a function to convert the width and height by rotating the image 180 degrees.

Unfortunately, that existing function doesn't do anything about the sourceX and sourceY. The plugin up until now (as far as I can tell) has always dealt with sourceX and sourceY of 0. I could use some tips on how to convert these coordinates. I'm happy to submit a pull request once I get everything working properly, but I'm a bit stumped at this part.

Use a web worker to generate preview

Is it possible to spawn a webworker to generate the image previews, as currently the image previews block the main thread and make the ui unresponsive especially when uploading many large files.

Maybe BlobBuilder object can be used for this?

How to use this on a <img>

Hi guys,

My requirement is to display correctly the images after the pic upload or when I get them from my server.

I'm trying to access to the , check the EXIF orientation and apply the correct CSS rotation (or something like that).

Guess what? Not having much success...

The problem is that I get the blob, image/png type but "data.exif" returns always false. Can you help me?

Here is my code:

function processImage(imgId) {
    var imgurl = document.getElementById(imgId).src;
    var imgHtml = document.getElementById(imgId);
    var blob = dataURItoBlob(getBase64Image(imgHtml));

    console.log(blob);

    loadImage.parseMetaData(
        blob,
        function (data) {           
            if(data.exif) {
                var orientation = data.exif.get('Orientation');
                alert(orientation);
            } else {
                alert('no exif');
            }
        }

    );   
}


function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    //return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    return dataURL;
}

function dataURItoBlob(dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs
    //alert('dataURI: ' + dataURI);
    var byteString = atob(dataURI.split(',')[1]);

    alert('byteString.length: ' + byteString.length);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
    alert('mimestring: ' + mimeString);

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    try {
        return new Blob([ab], {type: mimeString});
    } catch (e) {
        // The BlobBuilder API has been deprecated in favour of Blob, but older
        // browsers don't know about the Blob constructor
        // IE10 also supports BlobBuilder, but since the `Blob` constructor
        //  also works, there's no need to add `MSBlobBuilder`.
        var BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder;
        var bb = new BlobBuilder();
        bb.append(ab);
        return bb.getBlob(mimeString);
    }
}

Invalidates SSL Connection

It seams using this will cause an SSL connection to suddenly become 'unsecure' - i presume its because it adds a blob* element?

Is there a workaround?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.