Hello guys, I’m trying to create a photoshop panel that import image in a new layer from URL, I got this error “Error importing image: Error: invalid file token used”
Any can help please ?
This is the JS used code :
document.getElementById('importButton').addEventListener('click', async () => {
const imageUrl = document.getElementById('imageUrl').value;
if (imageUrl) {
try {
const response = await fetch(imageUrl);
if (!response.ok) throw new Error('Network response was not ok');
const blob = await response.blob();
const mimeType = blob.type;
const uxp = require('uxp');
const fs = uxp.storage.localFileSystem;
const batchPlay = require("photoshop").action.batchPlay;
const core = require("photoshop").core;
// Ensure file extension based on MIME type
let fileExtension = '';
if (mimeType === 'image/jpeg') {
fileExtension = '.jpg';
} else if (mimeType === 'image/png') {
fileExtension = '.png';
} else {
throw new Error('Unsupported image type');
}
// Create a temporary file path
const tempFolder = await fs.getTemporaryFolder();
const tempFile = await tempFolder.createFile(`tempImage${fileExtension}`, { overwrite: true });
// Write the blob to the temporary file
await tempFile.write(blob, { format: uxp.storage.formats.binary });
// Get the path of the temporary file
const tempFilePath = tempFile.nativePath;
// Place the image in the current document as a new layer using batchPlay within a modal scope
await core.executeAsModal(async () => {
await batchPlay([
{
_obj: "placeEvent",
target: {
_path: tempFilePath,
_kind: "local"
},
linked: false,
_options: {
dialogOptions: "dontDisplay"
}
}
], { synchronousExecution: true });
});
} catch (error) {
console.error('Error importing image:', error);
}
} else {
alert('Please enter a valid image URL.');
}
});
IIRC _path
requires a token and not an actual path. Try searching forum about this, there should be quite a few topics
Thank you for jumping really quick. I have updated the code, but something wrong there is no error in the App logs but the image was not imported, could you please take a look at my new code :
(feel free to adjust the code)
document.getElementById('importButton').addEventListener('click', async () => {
const imageUrl = document.getElementById('imageUrl').value;
if (imageUrl) {
try {
console.log('Fetching image from URL:', imageUrl);
const response = await fetch(imageUrl);
if (!response.ok) throw new Error('Network response was not ok');
const blob = await response.blob();
const mimeType = blob.type;
console.log('Fetched image blob:', blob);
const uxp = require('uxp');
const fs = uxp.storage.localFileSystem;
const { batchPlay } = require('photoshop').action;
const { core } = require('photoshop');
// Create a temporary file path with PNG extension
const tempFolder = await fs.getTemporaryFolder();
const tempFile = await tempFolder.createFile('tempImage.png', { overwrite: true });
// Create an image element to draw it on the canvas
const img = new Image();
img.src = URL.createObjectURL(blob);
img.onload = async () => {
console.log('Image loaded, drawing on canvas');
// Create a canvas element
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// Convert the canvas to a Blob
canvas.toBlob(async (pngBlob) => {
console.log('Canvas converted to PNG blob:', pngBlob);
// Write the PNG blob to the temporary file
await tempFile.write(pngBlob, { format: uxp.storage.formats.binary });
// Get the session token of the temporary file
const fileToken = await fs.createSessionToken(tempFile);
console.log('File token:', fileToken);
// Place the image in the current document as a new layer using batchPlay within a modal scope
await core.executeAsModal(async () => {
console.log('Executing batchPlay to place the image');
await batchPlay([
{
_obj: 'placeEvent',
target: {
_path: fileToken,
_kind: 'local'
},
linked: false,
_options: {
dialogOptions: 'dontDisplay'
}
}
], { synchronousExecution: true });
console.log('Image placed successfully');
});
}, 'image/png');
};
img.onerror = (e) => {
console.error('Error loading image:', e);
};
} catch (error) {
console.error('Error importing image:', error);
}
} else {
alert('Please enter a valid image URL.');
}
});
Additional information :
The image link trying to import from is : https://scenes.documents.cimpress.io/v3/scenes/texture/identity:generate?width=1000&height=1000
With this script everything looks fine, I have tried a different image link and gave it access from manifest file and it’s successfully loaded but not placed in the opened photoshop document, any can help ?
document.getElementById('importButton').addEventListener('click', async () => {
const imageUrl = document.getElementById('imageUrl').value.trim();
const urlPattern = /^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/;
if (!urlPattern.test(imageUrl)) {
alert('Please enter a valid image URL.');
return;
}
try {
console.log('Fetching image from URL:', imageUrl);
const response = await fetch(imageUrl);
if (!response.ok) {
throw new Error('Failed to fetch image. Please check the URL and try again.');
}
const blob = await response.blob();
const mimeType = blob.type;
console.log('Fetched image blob:', blob);
const uxp = require('uxp');
const fs = uxp.storage.localFileSystem;
const tempFolder = await fs.getTemporaryFolder();
const tempFile = await tempFolder.createFile('tempImage.png', { overwrite: true });
await tempFile.write(blob);
// Get the file token
const fileToken = await fs.createSessionToken(tempFile);
// Access Photoshop ActionManager
const { action, core } = require('photoshop');
const batchPlay = action.batchPlay;
// Execute batchPlay within a modal scope
await core.executeAsModal(async () => {
// Place the image into the current document using batchPlay
const result = await batchPlay(
[
{
_obj: "placeEvent",
null: {
_path: fileToken,
_kind: "local"
},
_place: {
_x: 100, // X coordinate where the image should be placed
_y: 100, // Y coordinate where the image should be placed
}
}
],
{ synchronousExecution: true }
);
console.log('Image placed successfully');
});
// Clean up temporary file after placing the image
await tempFile.delete();
} catch (error) {
console.error('Error importing image:', error);
alert('Failed to import image. Please try again later.');
}
});