Repository: renanbastos93/image-to-base64
Branch: master
Commit: 68be8a030296
Files: 13
Total size: 10.4 KB
Directory structure:
gitextract_x2zbnkjt/
├── .editorconfig
├── .github/
│ ├── FUNDING.yml
│ ├── dependabot.yml
│ └── workflows/
│ └── tests.yml
├── .gitignore
├── .npmrc
├── .travis.yml
├── LICENSE
├── README.md
├── browser.js
├── image-to-base64.js
├── package.json
└── test/
└── index.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: https://www.buymeacoffee.com/renanbastos93
================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
# Maintain dependencies for GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
# Maintain dependencies for npm
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "daily"
================================================
FILE: .github/workflows/tests.yml
================================================
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: Tests
on:
pull_request:
types: [opened, synchronize]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [8.x, 10.x, 12.x]
steps:
- uses: actions/checkout@v2.3.4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2.1.5
with:
node-version: ${{ matrix.node-version }}
- run: npm install -g mocha
- run: npm install
- run: npm test
================================================
FILE: .gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# package-lock.json from NPM
package-lock.json
yarn.lock
# macOS file
.DS_Store
*/**/.DS_Store
================================================
FILE: .npmrc
================================================
registry = https://registry.npmjs.org
email=renanbastos.tec@gmail.com
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- "9"
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2017 RENAN.BASTOS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# image-to-base64
Generate a base64 code from an image through a URL or a path.
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[](https://travis-ci.org/renanbastos93/image-to-base64)

[](https://www.codacy.com/app/renanbastos93/image-to-base64?utm_source=github.com&utm_medium=referral&utm_content=renanbastos93/image-to-base64&utm_campaign=Badge_Grade)
[npm-image]: https://img.shields.io/npm/v/image-to-base64.svg
[npm-url]: https://npmjs.org/package/image-to-base64
[downloads-image]: https://img.shields.io/npm/dm/image-to-base64.svg
[downloads-url]: https://npmjs.org/package/image-to-base64
## About
It's a thing you can use in many situations, for example you can just save the base64 string in your database and increment it in the front-end with the `
` tag in HTML.
## Getting Started
Installation:
```bash
npm i -S image-to-base64
```
Code Example:
```js
const imageToBase64 = require('image-to-base64');
//or
//import imageToBase64 from 'image-to-base64/browser';
imageToBase64("path/to/file.jpg") // Path to the image
.then(
(response) => {
console.log(response); // "cGF0aC90by9maWxlLmpwZw=="
}
)
.catch(
(error) => {
console.log(error); // Logs an error if there was one
}
)
```
Remember that you can also use an image URL as a parameter.
Code Example:
```js
imageToBase64("https://whatever-image/") // Image URL
.then(
(response) => {
console.log(response); // "iVBORw0KGgoAAAANSwCAIA..."
}
)
.catch(
(error) => {
console.log(error); // Logs an error if there was one
}
)
```
#### Browser Usage
You can import image-to-base64 using the `
```
Now you can use the module normally as in the JS examples above, but you can only use a URL and not a path.
### LICENSE
[MIT](https://opensource.org/licenses/MIT) © 2017 RENAN.BASTOS
================================================
FILE: browser.js
================================================
'use strict';
(function(escope) {
function base64ToBrowser(buffer) {
return window.btoa([].slice.call(new Uint8Array(buffer)).map(function(bin) { return String.fromCharCode(bin); }).join(''));
}
function imageToBase64Browser(urlOrImage, param) {
if (!('fetch' in window && 'Promise' in window)) {
return Promise.reject('[*] image-to-base64 is not compatible with your browser.');
}
return fetch(urlOrImage, param || {}).then(function(response) {
return response.arrayBuffer();
}).then(base64ToBrowser);
}
if (typeof module !== 'undefined') {
module.exports = imageToBase64Browser;
} else {
escope.imageToBase64 = imageToBase64Browser;
}
})(this);
================================================
FILE: image-to-base64.js
================================================
'use strict';
var fileSystem = require('fs');
var path = require('path');
var fetch = require('node-fetch');
function validUrl(url) {
return /http(s)?:\/\/(\w+:?\w*@)?(\S+)(:\d+)?((?<=\.)\w+)+(\/([\w#!:.?+=&%@!\-/])*)?/gi.test(url);
}
function validTypeImage(image) {
return /(?<=\S+)\.(jpg|png|jpeg)/gi.test(image);
}
function base64ToNode(buffer) {
return buffer.toString('base64');
}
function readFileAndConvert(fileName) {
if (fileSystem.statSync(fileName).isFile()) {
return base64ToNode(fileSystem.readFileSync(path.resolve(fileName)).toString('base64'));
}
return null;
}
function isImage(urlOrImage) {
if (validTypeImage(urlOrImage)) {
return Promise.resolve(readFileAndConvert(urlOrImage));
} else {
return Promise.reject('[*] An error occured: Invalid image [validTypeImage === false]');
}
}
function imageToBase64(urlOrImage) {
if (validUrl(urlOrImage)) {
return fetch(urlOrImage).then(function (response) {
return response.buffer();
}).then(base64ToNode);
} else {
return isImage(urlOrImage);
}
}
module.exports = imageToBase64;
================================================
FILE: package.json
================================================
{
"name": "image-to-base64",
"version": "2.2.0",
"description": "Generate a image to base64.",
"main": "image-to-base64.min.js",
"scripts": {
"minify:base": "uglifyjs image-to-base64.js -c -m -o image-to-base64.min.js",
"minify:browser": "uglifyjs browser.js -c -m -o browser.min.js",
"minify": "npm run minify:base && npm run minify:browser",
"test": "mocha ./test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/renanbastos93/image-to-base64.git"
},
"keywords": [
"node",
"nodejs",
"module convert base64 nodejs",
"image2base64",
"image-to-base64",
"convert-image-base64",
"convert",
"save",
"code",
"base64",
"image",
"webpack",
"loader",
"img",
"src",
"img src"
],
"author": "Renan Bastos - ",
"license": "MIT",
"bugs": {
"url": "https://github.com/renanbastos93/image-to-base64/issues"
},
"homepage": "https://github.com/renanbastos93/image-to-base64#readme",
"dependencies": {
"node-fetch": "^2.6.0"
},
"devDependencies": {
"uglify-js": "^3.9.1",
"mocha": "^7.1.1"
}
}
================================================
FILE: test/index.js
================================================
const image2base64 = require("./../image-to-base64.js");
const assert = require("assert");
const pt = require("path");
let url = "https://jaystack.com/wp-content/uploads/2015/12/nodejs-logo-e1497443346889.png";
let path = pt.resolve("test/nodejs.png");
let validBase64 = new RegExp("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{0,2}==)$","gim");
describe("must to be resolved the promise", function(){
it("get image of the url and convert to base64", function(){
image2base64(url)
.then(
(data) => {
assert(validBase64.test(data), true);
}
)
.catch((err) => assert(err, true));
});
it("get image of the path and convert to base64", function(){
image2base64(path)
.then(
(data) => {
assert(validBase64.test(data).test(data), true);
}
)
.catch((err) => assert(err, true));
});
});