MCPcopy
hub / github.com/wavetermdev/waveterm / saveImageFileWithNativeDialog

Function saveImageFileWithNativeDialog

emain/emain-ipc.ts:133–193  ·  view source on GitHub ↗
(
    sender: electron.WebContents,
    defaultFileName: string,
    mimeType: string,
    readStream: Readable
)

Source from the content-addressed store, hash-verified

131}
132
133function saveImageFileWithNativeDialog(
134 sender: electron.WebContents,
135 defaultFileName: string,
136 mimeType: string,
137 readStream: Readable
138) {
139 if (defaultFileName == null || defaultFileName == "") {
140 defaultFileName = "image";
141 }
142 const ww = electron.BrowserWindow.fromWebContents(sender);
143 if (ww == null) {
144 readStream.destroy();
145 return;
146 }
147 const mimeToExtension: { [key: string]: string } = {
148 "image/png": "png",
149 "image/jpeg": "jpg",
150 "image/gif": "gif",
151 "image/webp": "webp",
152 "image/bmp": "bmp",
153 "image/tiff": "tiff",
154 "image/heic": "heic",
155 "image/svg+xml": "svg",
156 };
157 function addExtensionIfNeeded(fileName: string, mimeType: string): string {
158 const extension = mimeToExtension[mimeType];
159 if (!path.extname(fileName) && extension) {
160 return `${fileName}.${extension}`;
161 }
162 return fileName;
163 }
164 defaultFileName = addExtensionIfNeeded(defaultFileName, mimeType);
165 electron.dialog
166 .showSaveDialog(ww, {
167 title: "Save Image",
168 defaultPath: defaultFileName,
169 filters: [{ name: "Images", extensions: ["png", "jpg", "jpeg", "gif", "webp", "bmp", "tiff", "heic"] }],
170 })
171 .then((file) => {
172 if (file.canceled) {
173 readStream.destroy();
174 return;
175 }
176 const writeStream = fs.createWriteStream(file.filePath);
177 readStream.pipe(writeStream);
178 writeStream.on("finish", () => {
179 console.log("saved file", file.filePath);
180 });
181 writeStream.on("error", (err) => {
182 console.log("error saving file (writeStream)", err);
183 readStream.destroy();
184 });
185 readStream.on("error", (err) => {
186 console.error("error saving file (readStream)", err);
187 writeStream.destroy();
188 });
189 })
190 .catch((err) => {

Callers 1

initIpcHandlersFunction · 0.85

Calls 3

addExtensionIfNeededFunction · 0.85
onMethod · 0.80
destroyMethod · 0.45

Tested by

no test coverage detected