Comments (11)
working TS version
/**
*
* @author Onur Zorluer
*
*/
function changeHeightWidth(
height: number,
maxHeight: number,
width: number,
maxWidth: number,
minWidth?: number,
minHeight?: number,
) {
if (width > maxWidth) {
height = Math.round((height * maxWidth) / width);
width = maxWidth;
}
if (height > maxHeight) {
width = Math.round((width * maxHeight) / height);
height = maxHeight;
}
if (minWidth && width < minWidth) {
height = Math.round((height * minWidth) / width);
width = minWidth;
}
if (minHeight && height < minHeight) {
width = Math.round((width * minHeight) / height);
height = minHeight;
}
return { height, width };
}
function resizeAndRotateImage(
image: HTMLImageElement,
maxWidth: number,
maxHeight: number,
minWidth: undefined | number,
minHeight: undefined | number,
compressFormat = 'jpeg',
quality = 100,
rotation = 0,
) {
const qualityDecimal = quality / 100;
const canvas = document.createElement('canvas');
let width = image.width;
let height = image.height;
const newHeightWidth = changeHeightWidth(height, maxHeight, width, maxWidth, minWidth, minHeight);
if (rotation && (rotation === 90 || rotation === 270)) {
canvas.width = newHeightWidth.height;
canvas.height = newHeightWidth.width;
} else {
canvas.width = newHeightWidth.width;
canvas.height = newHeightWidth.height;
}
width = newHeightWidth.width;
height = newHeightWidth.height;
const ctx = canvas.getContext('2d');
if (!ctx) {
return;
}
ctx.fillStyle = 'rgba(0, 0, 0, 0)';
ctx.fillRect(0, 0, width, height);
if (ctx.imageSmoothingEnabled && ctx.imageSmoothingQuality) {
ctx.imageSmoothingQuality = 'high';
}
if (rotation) {
ctx.rotate((rotation * Math.PI) / 180);
if (rotation === 90) {
ctx.translate(0, -canvas.width);
} else if (rotation === 180) {
ctx.translate(-canvas.width, -canvas.height);
} else if (rotation === 270) {
ctx.translate(-canvas.height, 0);
} else if (rotation === 0 || rotation === 360) {
ctx.translate(0, 0);
}
}
ctx.drawImage(image, 0, 0, width, height);
return canvas.toDataURL(`image/${compressFormat}`, qualityDecimal);
}
function b64toByteArrays(b64Data: string) {
const sliceSize = 512;
const byteCharacters = atob(
b64Data.toString().replace(/^data:image\/(png|jpeg|jpg|webp);base64,/, ''),
);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return byteArrays;
}
function b64toBlob(b64Data: string, contentType: string = 'image/jpeg') {
const byteArrays = b64toByteArrays(b64Data);
const blob = new Blob(byteArrays, {
lastModified: new Date(), // TODO: check problem
type: contentType,
} as BlobPropertyBag);
return blob;
}
function b64toFile(b64Data: string, fileName: string, contentType: string = 'image/jpeg') {
const byteArrays = b64toByteArrays(b64Data);
const file = new File(byteArrays, fileName, {
lastModified: new Date(), // TODO: check problem
type: contentType,
} as BlobPropertyBag);
return file;
}
function createResizedImage(
file: File,
maxWidth: number,
maxHeight: number,
compressFormat: string,
quality: number,
rotation: number,
responseUriFunc: (blob: string | File | Blob) => void,
outputType = 'base64',
minWidth?: number,
minHeigh?: number,
) {
const reader = new FileReader();
if (file) {
if (file.type && !file.type.includes('image')) {
throw Error('File Is NOT Image!');
} else {
reader.readAsDataURL(file);
reader.onload = () => {
const image = new Image();
image.src = reader.result?.toString() || '';
image.onload = function () {
const resizedDataUrl = resizeAndRotateImage(
image,
maxWidth,
maxHeight,
minWidth,
minHeigh,
compressFormat,
quality,
rotation,
);
if (!resizedDataUrl) {
return; // TODO: improve typings
}
const contentType = `image/${compressFormat}`;
switch (outputType) {
case 'blob':
const blob = b64toBlob(resizedDataUrl, contentType);
responseUriFunc(blob);
break;
case 'base64':
responseUriFunc(resizedDataUrl);
break;
case 'file':
const fileName = file.name;
const fileNameWithoutFormat = fileName
.toString()
.replace(/(png|jpeg|jpg|webp)$/i, '');
const newFileName = fileNameWithoutFormat.concat(compressFormat.toString());
const newFile = b64toFile(resizedDataUrl, newFileName, contentType);
responseUriFunc(newFile);
break;
default:
responseUriFunc(resizedDataUrl);
}
};
};
reader.onerror = (error: any) => {
throw Error(error);
};
}
} else {
throw Error('File Not Found!');
}
}
export { createResizedImage };
from react-image-file-resizer.
yo pude solucionarlo asi:
-
Copiar todo lo que esta en el index : https://github.com/onurzorluer/react-image-file-resizer/blob/3a0fab44211f985aaf048b4fa71027b7149da90e/src/index.js
-
la parte donde dice exporta default lo eliminas, luego agregas esto en tu class Resizer, asi:
static imageFileResizer = (file, maxWidth, maxHeight, compressFormat, quality, rotation, responseUriFunc, outputType, minWidth, minHeight) => { return Resizer.createResizedImage( file, maxWidth, maxHeight, compressFormat, quality, rotation, responseUriFunc, outputType, minWidth, minHeight, ); }
-
Esto pones fuera de Class Resizer :
const resizeFile = (file) => new Promise((resolve) => { Resizer.imageFileResizer(file, 125, 125, "png", 100, 0, (uri) => { resolve(uri) }, "file"); });
const imageResize = async (file) => { try { const resFile = await resizeFile(file) console.info("todo bien", resFile) return resFile } catch (err) { console.error("esto es un error", err) throw new Error("Return error"); } }
export { imageResize }
-
Asi lo uso:
a)import {imageResize} from './utils/imageResize'
b)imageResize(event.target.files[0]).then((convertedFile) => { console.log(convertedFile) })
from react-image-file-resizer.
yo pude solucionarlo asi:
- Copiar todo lo que esta en el index : https://github.com/onurzorluer/react-image-file-resizer/blob/3a0fab44211f985aaf048b4fa71027b7149da90e/src/index.js
- la parte donde dice exporta default lo eliminas, luego agregas esto en tu class Resizer, asi:
static imageFileResizer = (file, maxWidth, maxHeight, compressFormat, quality, rotation, responseUriFunc, outputType, minWidth, minHeight) => { return Resizer.createResizedImage( file, maxWidth, maxHeight, compressFormat, quality, rotation, responseUriFunc, outputType, minWidth, minHeight, ); }
- Esto pones fuera de Class Resizer :
const resizeFile = (file) => new Promise((resolve) => { Resizer.imageFileResizer(file, 125, 125, "png", 100, 0, (uri) => { resolve(uri) }, "file"); });
const imageResize = async (file) => { try { const resFile = await resizeFile(file) console.info("todo bien", resFile) return resFile } catch (err) { console.error("esto es un error", err) throw new Error("Return error"); } }
export { imageResize }
- Asi lo uso:
a)import {imageResize} from './utils/imageResize'
b)imageResize(event.target.files[0]).then((convertedFile) => { console.log(convertedFile) })
Worked for me, thank you 🔥
from react-image-file-resizer.
Nevermind. This is most definitely a problem with Vitejs or more specifically whatever build tools they're using. I moved a minimal reproduction over to Create React App and hey what do you know... It built and it works wonderfully. Thanks, again, for this wonderful utility! Have a great day!
from react-image-file-resizer.
Nevermind. This is most definitely a problem with Vitejs or more specifically whatever build tools they're using. I moved a minimal reproduction over to Create React App and hey what do you know... It built and it works wonderfully. Thanks, again, for this wonderful utility! Have a great day!
Hi ADParris, dying to know how you fixed this issue, did you have to do something to vite config..?
Much appreciated.
from react-image-file-resizer.
Thank you. I did implemented it, and worked; and will be filing up a version with TypeScript rather soon.
from react-image-file-resizer.
I'm still having this issue.
from react-image-file-resizer.
Gracias! This worked great.
from react-image-file-resizer.
working TS version
/** * * @author Onur Zorluer * */ function changeHeightWidth( height: number, maxHeight: number, width: number, maxWidth: number, minWidth?: number, minHeight?: number, ) { if (width > maxWidth) { height = Math.round((height * maxWidth) / width); width = maxWidth; } if (height > maxHeight) { width = Math.round((width * maxHeight) / height); height = maxHeight; } if (minWidth && width < minWidth) { height = Math.round((height * minWidth) / width); width = minWidth; } if (minHeight && height < minHeight) { width = Math.round((width * minHeight) / height); height = minHeight; } return { height, width }; } function resizeAndRotateImage( image: HTMLImageElement, maxWidth: number, maxHeight: number, minWidth: undefined | number, minHeight: undefined | number, compressFormat = 'jpeg', quality = 100, rotation = 0, ) { const qualityDecimal = quality / 100; const canvas = document.createElement('canvas'); let width = image.width; let height = image.height; const newHeightWidth = changeHeightWidth(height, maxHeight, width, maxWidth, minWidth, minHeight); if (rotation && (rotation === 90 || rotation === 270)) { canvas.width = newHeightWidth.height; canvas.height = newHeightWidth.width; } else { canvas.width = newHeightWidth.width; canvas.height = newHeightWidth.height; } width = newHeightWidth.width; height = newHeightWidth.height; const ctx = canvas.getContext('2d'); if (!ctx) { return; } ctx.fillStyle = 'rgba(0, 0, 0, 0)'; ctx.fillRect(0, 0, width, height); if (ctx.imageSmoothingEnabled && ctx.imageSmoothingQuality) { ctx.imageSmoothingQuality = 'high'; } if (rotation) { ctx.rotate((rotation * Math.PI) / 180); if (rotation === 90) { ctx.translate(0, -canvas.width); } else if (rotation === 180) { ctx.translate(-canvas.width, -canvas.height); } else if (rotation === 270) { ctx.translate(-canvas.height, 0); } else if (rotation === 0 || rotation === 360) { ctx.translate(0, 0); } } ctx.drawImage(image, 0, 0, width, height); return canvas.toDataURL(`image/${compressFormat}`, qualityDecimal); } function b64toByteArrays(b64Data: string) { const sliceSize = 512; const byteCharacters = atob( b64Data.toString().replace(/^data:image\/(png|jpeg|jpg|webp);base64,/, ''), ); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return byteArrays; } function b64toBlob(b64Data: string, contentType: string = 'image/jpeg') { const byteArrays = b64toByteArrays(b64Data); const blob = new Blob(byteArrays, { lastModified: new Date(), // TODO: check problem type: contentType, } as BlobPropertyBag); return blob; } function b64toFile(b64Data: string, fileName: string, contentType: string = 'image/jpeg') { const byteArrays = b64toByteArrays(b64Data); const file = new File(byteArrays, fileName, { lastModified: new Date(), // TODO: check problem type: contentType, } as BlobPropertyBag); return file; } function createResizedImage( file: File, maxWidth: number, maxHeight: number, compressFormat: string, quality: number, rotation: number, responseUriFunc: (blob: string | File | Blob) => void, outputType = 'base64', minWidth?: number, minHeigh?: number, ) { const reader = new FileReader(); if (file) { if (file.type && !file.type.includes('image')) { throw Error('File Is NOT Image!'); } else { reader.readAsDataURL(file); reader.onload = () => { const image = new Image(); image.src = reader.result?.toString() || ''; image.onload = function () { const resizedDataUrl = resizeAndRotateImage( image, maxWidth, maxHeight, minWidth, minHeigh, compressFormat, quality, rotation, ); if (!resizedDataUrl) { return; // TODO: improve typings } const contentType = `image/${compressFormat}`; switch (outputType) { case 'blob': const blob = b64toBlob(resizedDataUrl, contentType); responseUriFunc(blob); break; case 'base64': responseUriFunc(resizedDataUrl); break; case 'file': const fileName = file.name; const fileNameWithoutFormat = fileName .toString() .replace(/(png|jpeg|jpg|webp)$/i, ''); const newFileName = fileNameWithoutFormat.concat(compressFormat.toString()); const newFile = b64toFile(resizedDataUrl, newFileName, contentType); responseUriFunc(newFile); break; default: responseUriFunc(resizedDataUrl); } }; }; reader.onerror = (error: any) => { throw Error(error); }; } } else { throw Error('File Not Found!'); } } export { createResizedImage };
Thanks man!
from react-image-file-resizer.
Is there an NPM version that just works with Vite or are we required to manually pull in this code?
from react-image-file-resizer.
Thank you the TS version works for me!
from react-image-file-resizer.
Related Issues (20)
- PNG transparency is lost even when using compressFormat PNG HOT 3
- Force resize HOT 1
- why is the rotation is not "set"
- No response (success nor error) with HEIC format. HOT 9
- We need a fixed aspact ratio attribute.
- Why a class?
- FileReader': parameter 1 is not of type 'Blob'. HOT 7
- react version 17.0.2 HOT 1
- Indeterminate result HOT 3
- imageFileResizer not a function after building with Vite HOT 14
- Support for GIF and Animated WebP HOT 2
- Is there anything underway to port this to Vuejs3 (or does it exist elsewhere)? HOT 1
- Image is getting pixeled after resizing it HOT 1
- Quality not affecting PNG format HOT 1
- add support for array or similar for outputType
- keep metadata
- Can't find variable: FileReader
- Resize algorithm
- File extensions concatenated
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-image-file-resizer.