mobile: add optional image compression on upload

This commit is contained in:
ammarahm-ed
2023-08-14 14:10:33 +05:00
committed by Abdullah Atta
parent 6504beda78
commit d97be2d4fb
6 changed files with 272 additions and 10 deletions

View File

@@ -48,3 +48,22 @@ export async function compressToBase64(path, type) {
RNFetchBlob.fs.unlink(response.uri.replace("file://", "")).catch(console.log);
return base64;
}
export async function compressToFile(path, type) {
const response = await ImageResizer.createResizedImage(
path,
1080,
9999,
type,
85,
0,
undefined,
true,
{
mode: "contain",
onlyScaleDown: true
}
);
RNFetchBlob.fs.unlink(path.replace("file://", "")).catch(console.log);
return response.uri;
}

View File

@@ -0,0 +1,173 @@
/*
This file is part of the Notesnook project (https://notesnook.com/)
Copyright (C) 2023 Streetwriters (Private) Limited
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React, { useState } from "react";
import { Image, TouchableOpacity, View } from "react-native";
import { ImagePickerResponse } from "react-native-image-picker";
import { useThemeColors } from "../../../../../../packages/theme/dist";
import { presentSheet } from "../../../services/event-manager";
import { SIZE } from "../../../utils/size";
import { Button } from "../../ui/button";
import { IconButton } from "../../ui/icon-button";
import { Notice } from "../../ui/notice";
import Paragraph from "../../ui/typography/paragraph";
export default function AttachImage({
response,
onAttach,
close
}: {
response: ImagePickerResponse;
onAttach: ({ compress }: { compress: boolean }) => void;
close: ((ctx?: string | undefined) => void) | undefined;
}) {
const { colors } = useThemeColors();
const [compress, setCompress] = useState(true);
const image = response.assets?.[0];
const width = image?.width || 0;
const height = image?.height || 0;
const ratio = width / height;
return (
<View
style={{
alignItems: "center",
paddingHorizontal: 12
}}
>
{image ? (
<View
style={{
width: "100%",
borderRadius: 10,
backgroundColor: "black",
alignItems: "center",
justifyContent: "center",
marginBottom: 10
}}
>
<Image
source={{
uri: image.uri
}}
resizeMode="contain"
style={{
width: 300 * ratio,
height: (300 * ratio) / ratio,
backgroundColor: "black"
}}
/>
</View>
) : null}
<TouchableOpacity
activeOpacity={1}
style={{
flexDirection: "row",
alignSelf: "center",
marginBottom: 12,
alignItems: "center",
width: "100%"
}}
onPress={() => {
setCompress(!compress);
}}
>
<IconButton
size={SIZE.lg}
name={compress ? "checkbox-marked" : "checkbox-blank-outline"}
color={compress ? colors.primary.accent : colors.primary.icon}
customStyle={{
width: 25,
height: 25
}}
onPress={() => {
setCompress(!compress);
}}
/>
<Paragraph
style={{
flexShrink: 1,
marginLeft: 3
}}
size={SIZE.sm}
>
Compress image (recommended)
</Paragraph>
</TouchableOpacity>
{!compress ? (
<Notice
type="alert"
text="Images uploaded without compression are slow to load and take more bandwidth. We recommend compressing images unless you need image in original quality."
size="small"
style={{
width: "100%",
marginBottom: 12
}}
/>
) : (
<Notice
type="information"
text="Compressed images are uploaded in FULL HD resolution and are good enough for most use cases."
size="small"
style={{
width: "100%",
marginBottom: 12
}}
/>
)}
<Button
title="Add image"
type="accent"
width="100%"
onPress={() => {
onAttach({
compress
});
}}
/>
</View>
);
}
AttachImage.present = (response: ImagePickerResponse) => {
return new Promise((resolve) => {
let resolved = false;
presentSheet({
component: (ref, close, update) => (
<AttachImage
response={response}
close={close}
onAttach={(result) => {
resolved = true;
console.log("closing");
resolve(result);
close?.();
}}
/>
),
onClose: () => {
if (resolved) return;
resolve(undefined);
}
});
});
};

View File

@@ -17,10 +17,10 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useThemeColors } from "@notesnook/theme";
import React from "react";
import { View } from "react-native";
import { getContainerBorder } from "../../../utils/colors";
import { View, ViewStyle } from "react-native";
import { useThemeColors } from "@notesnook/theme";
import { SIZE } from "../../../utils/size";
import { IconButton } from "../icon-button";
import Paragraph from "../typography/paragraph";
@@ -30,13 +30,15 @@ export interface NoticeProps {
text: string;
size?: "small" | "large";
selectable?: boolean;
style?: ViewStyle;
}
export const Notice = ({
type = "alert",
text,
size = "large",
selectable
selectable,
style
}: NoticeProps) => {
const { colors } = useThemeColors();
const isSmall = size === "small";
@@ -49,7 +51,8 @@ export const Notice = ({
backgroundColor: colors.secondary.background,
borderRadius: isSmall ? 5 : 10,
alignItems: "flex-start",
...getContainerBorder(colors.secondary.background)
...getContainerBorder(colors.secondary.background),
...style
}}
>
<IconButton

View File

@@ -24,7 +24,11 @@ import RNFetchBlob from "react-native-blob-util";
import DocumentPicker from "react-native-document-picker";
import { launchCamera, launchImageLibrary } from "react-native-image-picker";
import { db } from "../../../common/database";
import { compressToBase64 } from "../../../common/filesystem/compress";
import {
compressToBase64,
compressToFile
} from "../../../common/filesystem/compress";
import AttachImage from "../../../components/dialogs/attach-image-dialog";
import {
ToastManager,
eSendEvent,
@@ -215,6 +219,21 @@ const handleImageResponse = async (response, options) => {
}
let image = response.assets[0];
const compress = await AttachImage.present(response);
const isPng = /(png)/g.test(image.type);
const isJpeg = /(jpeg|jpg)/g.test(image.type);
if (compress && (isPng || isJpeg)) {
image.uri = await compressToFile(
Platform.OS === "ios" ? "file://" + image.uri : image.uri,
isPng ? "PNG" : "JPEG"
);
const stat = await RNFetchBlob.fs.stat(image.uri.replace("file://", ""));
image.fileSize = stat.size;
}
if (image.fileSize > IMAGE_SIZE_LIMIT) {
ToastManager.show({
title: "File too large",
@@ -242,8 +261,7 @@ const handleImageResponse = async (response, options) => {
});
if (!(await attachFile(uri, hash, image.type, fileName, options))) return;
const isPng = /(png)/g.test(image.type);
const isJpeg = /(jpeg|jpg)/g.test(image.type);
if (isPng || isJpeg) {
b64 =
`data:${image.type};base64, ` +

View File

@@ -23,6 +23,7 @@ import { Platform } from "react-native";
import RNFetchBlob from "react-native-blob-util";
import { DatabaseLogger, db } from "../common/database";
import { IOS_APPGROUPID } from "./constants";
import { compressToFile } from "../common/filesystem/compress";
const santizeUri = (uri) => {
uri = decodeURI(uri);
@@ -92,10 +93,22 @@ async function createNotes(bundle) {
);
}
}
const compress = bundle.compress;
for (const file of bundle.files) {
const uri =
Platform.OS === "ios" ? santizeUri(file.value) : `${file.value}`;
let uri = Platform.OS === "ios" ? santizeUri(file.value) : `${file.value}`;
const isPng = /(png)/g.test(file.type);
const isJpeg = /(jpeg|jpg)/g.test(file.type);
if ((isPng || isJpeg) && compress) {
console.log(uri, "before compressed");
uri = await compressToFile("file://" + uri, isPng ? "PNG" : "JPEG");
uri = `${uri.replace("file://", "")}`;
}
console.log(uri, "after compressed");
const hash = await Sodium.hashFile({
uri: uri,
type: "cache"

View File

@@ -33,6 +33,7 @@ import {
SafeAreaView,
ScrollView,
StatusBar,
Text,
TouchableOpacity,
View,
useWindowDimensions
@@ -137,6 +138,7 @@ const ShareView = () => {
const [rawFiles, setRawFiles] = useState([]);
const [kh, setKh] = useState(0);
const [compress, setCompress] = useState(true);
globalThis["IS_SHARE_EXTENSION"] = true;
const onKeyboardDidShow = (event) => {
let height = Dimensions.get("window").height - event.endCoordinates.screenY;
@@ -294,7 +296,8 @@ const ShareView = () => {
files: rawFiles,
note: _note,
notebooks: useShareStore.getState().selectedNotebooks,
tags: useShareStore.getState().selectedTags
tags: useShareStore.getState().selectedTags,
compress
});
try {
@@ -551,6 +554,39 @@ const ShareView = () => {
>
Tap to remove an attachment.
</Paragraph>
<TouchableOpacity
activeOpacity={1}
style={{
flexDirection: "row",
alignSelf: "center",
alignItems: "center",
width: "100%",
marginTop: 6
}}
onPress={() => {
setCompress(!compress);
}}
>
<Icon
size={20}
name={
compress ? "checkbox-marked" : "checkbox-blank-outline"
}
color={
compress ? colors.primary.accent : colors.primary.icon
}
/>
<Text
style={{
flexShrink: 1,
marginLeft: 3,
fontSize: 12
}}
>
Compress image (recommended)
</Text>
</TouchableOpacity>
</View>
) : null}
<View