base64Image字串 轉 jpg
@param  {String} base64ImageData image src中的字串
@param  {String} filename        路徑與檔名，需要以.jpg結尾
@return {Promise}                Promise
13346
function base64tpjpg(base64ImageData, filename) {
    var promise = new Promise(function(resolve, reject) {
        var base64Data = base64ImageData.replace(/^data:image\/\w+;base64,/, "");
        var dataBuffer = new Buffer(base64Data, 'base64');
        fs.writeFile(tmpimage, dataBuffer, function(err) {
            if (err) {
                reject(err);
            } else {
                execFile(mozjpeg, ['-outfile', filename, tmpimage], function(err) {
                    if (err) {
                        reject(err);
                    } else {
                        fs.unlink(tmpimage, function(err) {
                            resolve(filename);
                        });
                    }
                });
            }
        });
    });
    return promise;
}
259053
function toBase64 (media) {
  return new Promise((resolve, reject) => {
    if (isBase64(media)) {
      resolve(media)
    } else if (isURL(media)) {
      urlToBase64(media)
      .then(data => resolve(data))
      .catch(error => reject(error))
    } else if (isFile(media)) {
      fileToBase64(media)
      .then(data => resolve(data))
      .catch(error => reject(error))
    } else if (isBuffer(media)) {
      const base64 = media.toString('base64')
      resolve(base64)
    } else {
      reject('Error: toBase64(): cannot convert media')
    }
  })
}
239650
function base64toBlob(base64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 512;

        var byteCharacters = atob(base64Data);
        var byteArrays = [];

        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);
            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }

        return new Blob(byteArrays, {type: contentType});
    }
57798
function(fileName) {
                let file = assets[fileName] || {};
                fileName = basePath + "/" + fileName.replace(/\\/g, '/');
                let key = path.posix.join(uploadPath, fileName);

                return new Promise((resolve, reject) => {
                    let begin = Date.now();
                    cos.putObject(
                        {
                            Bucket: bucket,
                            Region: region,
                            Key: key,
                            Body: fs.createReadStream(file.existsAt),
                            ContentLength: fs.statSync(file.existsAt).size
                        },
                        function(err, body) {
                            uploadedFiles++;
                            spinner.text = tip(uploadedFiles, totalFiles);

                            if (err) return reject(err);
                            body.duration = Date.now() - begin;
                            resolve(body);
                        }
                    );
                });
            }
922825
public String createContainingBase64Value(String basename, String key) {
        String file;
        Object value = value(key);
        if (value == null) {
            throw new SlimFixtureException(false, "No value for key: " + key);
        } else if (value instanceof String) {
            file = createFileFromBase64(basename, (String) value);
        } else {
            throw new SlimFixtureException(false, "Value for key: " + key + " is not a String, but: " + value);
        }
        return file;
    }
991452
function (filename, fn) {

		fn = fn || function () {};

		this._image.pack().pipe(fs.createWriteStream(filename)).once('close', function () {
			this._image.removeListener('error', fn);
			fn(undefined, this);
		}.bind(this)).once('error', function (err) {
			this._image.removeListener('close', fn);
			fn(err, this);
		}.bind(this));
	}
306165
function fetch(filename) {
        var att = atts[filename];
        var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +
          '?rev=' + doc._rev;
        return ajaxPromise(opts, {
          method: 'GET',
          url: genDBUrl(host, path),
          binary: true
        }).then(function (blob) {
          if (opts.binary) {
            return blob;
          }
          return new Promise(function (resolve) {
            pouchdbBinaryUtils.blobOrBufferToBase64(blob, resolve);
          });
        }).then(function (data) {
          delete att.stub;
          delete att.length;
          att.data = data;
        });
      }
346700
public static Document parseBase64(String base64Data, Element instruction)
            throws Exception {
        byte[] imageData = Base64.decodeBase64(base64Data);
        ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
        StringWriter swLogger = new StringWriter();
        PrintWriter pwLogger = new PrintWriter(swLogger);
        return parse(bais, instruction, pwLogger);
    }
1018686
public static String encodeBase64(File imageFile) throws IOException{
        BufferedImage bi = ImageIO.read(imageFile);
        String type = FileKit.getFileExtension(imageFile).toLowerCase();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi,type, baos);
        return Base64Kit.encode(baos.toByteArray());
    }
307082
function readFile(filename) {
	return new Promise(
		(resolve, reject) => fs.readFile(filename, 'utf8',
			(error, data) => error ? reject(error) : resolve(data)
		)
	);
}
547309
function imageToImageData ( image ) {
	if ( image instanceof HTMLImageElement ) {
		// http://stackoverflow.com/a/3016076/229189
		if ( ! image.naturalWidth || ! image.naturalHeight || image.complete === false ) {
			throw new Error( "This this image hasn't finished loading: " + image.src );
		}

		const canvas = new Canvas( image.naturalWidth, image.naturalHeight );
		const ctx = canvas.getContext( '2d' );
		
		ctx.drawImage( image, 0, 0, canvas.width, canvas.height );

		const imageData = ctx.getImageData( 0, 0, canvas.width, canvas.height );

		if ( imageData.data && imageData.data.length ) {
			if ( typeof imageData.width === 'undefined' ) {
				imageData.width = image.naturalWidth;
			}

			if ( typeof imageData.height === 'undefined' ) {
				imageData.height = image.naturalHeight;
			}
		}
		
		return imageData;
	} else {
		throw new Error( 'This object does not seem to be an image.' );
		return;
	}
}
1180875
public static String getImageAsBase64(@Nonnull File file) throws IOException {
        String contentType = getContentType(file);
        BufferedImage bufferedImage = ImageIO.read(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, contentType.split("/")[1], bos);
        byte[] imageBytes = bos.toByteArray();

        return Base64.getEncoder().encodeToString(imageBytes);
    }
1216955
function shrinkImage(base64Image, targetSize) {

  return new Promise( (resolve, reject) => {

    let canvas  = document.createElement('canvas');
    let image   = new Image();

    image.onload = _ => {

      canvas.height = image.naturalHeight;
      canvas.width  = image.naturalWidth;

      canvas.getContext('2d').drawImage(image, 0, 0);

      return resolve(shrink(95));

      function shrink(quality) {
        let redrawnImage = canvas.toDataURL('image/jpeg', quality/100);

        // 1. Stop at zero because quality can't get any worse!
        // 2. Base64 encoded images are 1.33 times larger than once they are converted back to a blob.
        return quality !== 0 && redrawnImage.length / 1.33 > targetSize ? shrink(quality - 5) : redrawnImage;
      }

    };

    image.src = base64Image;

  });
}
873191
function(fileName, content) {
                return Promise()
                .then(function() {
                    var filePath = PathUtils.resolveInRoot(outputFolder, fileName);

                    return fs.ensureFile(filePath)
                    .then(function() {
                        return fs.writeFile(filePath, content);
                    });
                });
            }
414451
public static boolean generateImage(String imgStr, String imgFilePath) {
        if (imgStr == null) //图像数据为空
            return false;

        try {
            //Base64解码
            byte[] b = Base64.decodeBase64(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
182720
def get_imageblock(filename, format=''):
    
    _, extension = os.path.splitext(filename)

    with open(filename, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')

    return '\n\n.. raw:: html\n\n\t<img src="data:image/' + (format if format else extension[1:]) + ';base64,' + encoded_string +'">\n'
365012
function write(filename, data) {
  return Promise.fromCallback(function (done) {
    debug('write', filename);
    fs.writeFile(filename, data, done);
  });
}