I need a way to incrase resolution of capture so it prints nicely.
const window = BrowserWindow.getFocusedWindow()
const saveDialogReturnValue = await dialog.showSaveDialog(window, {
defaultPath: "image.jpg",
})
const capture = await window.capturePage()
await writeFile(saveDialogReturnValue.filePath, capture.toJPEG(100))
})
Thanks for helping out!
Related
I have a simple node script to fetch tif image, use sharp to convert the image to jpeg and generate data:image/jpeg;base64 src for browser. The reason is to enable tiff image in browsers that do not support tif/tiff images.
In node this works great.
import sharp from "sharp";
import fetch from "node-fetch";
let link =
"https://people.math.sc.edu/Burkardt/data/tif/at3_1m4_01.tif";
// fetch tif image and save it as a buffer
async function fetchTifBuffer(link) {
const tifImg = await fetch(link);
const buffer = await tifImg.buffer();
return buffer;
}
// convert to png image save to buffer and save as base64
async function tifToPngToBase64(link) {
let inputImgBuffer = await fetchTifBuffer(link);
const buff = await sharp(inputImgBuffer).toFormat("jpeg").toBuffer();
let base64data = buff.toString("base64");
let imgsrc = "data:image/jpeg;base64," + base64data.toString("base64");
console.log(imgsrc);
// use in browser <img src="data:image/jpeg;base64,/9j/2wBDAAYEBQYFBAY ...==" alt="image" />
}
tifToPngToBase64(link);
I would like to implement this in SvelteKit. But I have no idea how to get buffer from SvelteKit fetch response. Any ideas?
Ok, so I figured it out by myself. SvelteKit fetch response has an arrayBuffer, so all that is needed is to convert the arraybuffer to the buffer.
This is the relevant SvelteKit endpoint:
// img.js
import sharp from "sharp";
export const get = async () => {
const res = await fetch(
"https://people.math.sc.edu/Burkardt/data/tif/at3_1m4_01.tif"
);
const abuffer = await res.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(abuffer));
const buff = await sharp(buffer).toFormat("jpeg").toBuffer();
let base64data = buff.toString("base64");
let src = `data:image/jpeg;base64,${base64data.toString("base64")}`;
let img = `<img style='display:block; width:100px;height:100px;' id='base64image'
src='${src}' />`;
return {
body: {
img,
},
};
};
and this is the SvelteKit component which uses the endpont:
// img.svelte
<script>
export let img;
</script>
{#html img}
I'm trying to set up localStorage when a user registers,
but it only generates the file with no key, values.
If I run npx playwright codegen --save-storage=formsData.json
works fine and generates the key,values but the generated code is very different
and I don't see how localStorage is created.
What I'm doing wrong, or not doing ?
This is my test code:
const { test, expect } = require('#playwright/test');
const { buildUser } = require('./utils/generateUser');
test.describe('Register Form', () => {
test('displays register form and can register user', async ({ browser }) => {
const user = await buildUser();
const page = await browser.newPage();
await page.goto('http://localhost:3000/register');
await expect(page).toHaveURL('http://localhost:3000/register');
const firstNameInput = page.locator('[placeholder="Nombre"]');
const lastNameInput = page.locator('[placeholder="Apellidos"]');
const emailInput = page.locator('[placeholder="Email"]');
const passwordInput = page.locator('[placeholder="Contraseña"]');
const repeatPasswordInput = page.locator('[placeholder="Repite la contraseña"]');
const registerButton = page.locator('text=Adelante');
const termsCheckbox = page.locator('input[type="checkbox"]').first();
const privacyCheckbox = page.locator('input[type="checkbox"]').last();
const modalWindow = page.locator('.styles__ContentWrapper-n48cq5-0');
const modalButton = page.locator('text=Aceptar');
await expect(firstNameInput).toBeEmpty();
await expect(lastNameInput).toBeEmpty();
await expect(emailInput).toBeEmpty();
await expect(passwordInput).toBeEmpty();
await expect(repeatPasswordInput).toBeEmpty();
await expect(registerButton).toBeDisabled();
await expect(termsCheckbox).not.toBeChecked();
await expect(privacyCheckbox).not.toBeChecked();
await expect(modalWindow).toBeHidden();
await firstNameInput.fill(user.nombre);
await lastNameInput.fill(user.apellido);
await emailInput.fill(user.email);
await passwordInput.fill('12341234');
await repeatPasswordInput.fill('12341234');
await termsCheckbox.check();
await privacyCheckbox.click();
await expect(modalWindow).toBeVisible();
await page.press(':nth-match(input[type="checkbox"], 2)', 'Tab');
await page.press('text=info#coinscrap.com', 'Tab');
await await modalButton.click();
await expect(registerButton).toBeEnabled();
await registerButton.click();
await page.context().storageState({ path: 'formsData.json' });
await browser.close();
});
});
This is what playwright codegen does:
const { test, expect } = require('#playwright/test');
test('test', async ({ page }) => {
// Go to http://localhost:3000/register
await page.goto('http://localhost:3000/register');
// Click [placeholder="Nombre"]
await page.click('[placeholder="Nombre"]');
// Fill [placeholder="Nombre"]
await page.fill('[placeholder="Nombre"]', 'Pascale');
// Click [placeholder="Apellidos"]
await page.click('[placeholder="Apellidos"]');
// Fill [placeholder="Apellidos"]
await page.fill('[placeholder="Apellidos"]', 'Gusikowski');
// Click [placeholder="Email"]
await page.click('[placeholder="Email"]');
// Fill [placeholder="Email"]
await page.fill('[placeholder="Email"]', 'Pascale_Gusikowski86#gmail.com');
// Click [placeholder="Contraseña"]
await page.click('[placeholder="Contraseña"]');
// Fill [placeholder="Contraseña"]
await page.fill('[placeholder="Contraseña"]', '12341234');
// Click [placeholder="Repite la contraseña"]
await page.click('[placeholder="Repite la contraseña"]');
// Fill [placeholder="Repite la contraseña"]
await page.fill('[placeholder="Repite la contraseña"]', '12341234');
// Check input[type="checkbox"]
await page.check('input[type="checkbox"]');
// Click text=1.1 -Decisiones automatizadas, perfiles y lógica aplicada Los datos recogidos me
await page.click('text=1.1 -Decisiones automatizadas, perfiles y lógica aplicada Los datos recogidos me');
// Press End
await page.press('text=You need to enable JavaScript to run this app. Crea una cuenta AdelanteHe l', 'End');
// Click text=Aceptar
await page.click('text=Aceptar');
// Click text=Adelante
await Promise.all([
page.waitForNavigation(/*{ url: 'http://localhost:3000/internal/banks/start' }*/),
page.click('text=Adelante')
]);
});
There's no code where localStorage is created.
I need to do it programmatically.
I've also tried with:
const localStorage = await page.evaluate(() => JSON.stringify(window.localStorage));
fs.writeFileSync('formsData.json', localStorage);
It generates the file but didn't generate keys, values.
localStorage (DOMStorage) is unrelated to the form you submit. When you submit the form, a POST request is typically issued to the server, sending on this data to the backend. It looks like your page has additional JavaScript code that stores these values into localStorage at some point. Your localStorage does not have these values at the time you save it, so you should figure out how to trigger this code on your page and how to wait for it. You can open DevTools and evaluate "localStorage" in console or pick it in the Application tab to see when and why these values make their way into the local storage.
I tried to share data between Safari browser and standalone PWA on iPhone12 with iOS 14.3.
The information, that this should work are here: https://firt.dev/ios-14/
I#ve tried this: https://www.netguru.com/codestories/how-to-share-session-cookie-or-state-between-pwa-in-standalone-mode-and-safari-on-ios
Without success.
Are there any suggestions to running this? Or is it not possible ...
This is the code
const CACHE_NAME = "auth";
const TOKEN_KEY = "token";
const FAKE_TOKEN = "sRKWQu6hCJgR25lslcf5s12FFVau0ugi";
// Cache Storage was designed for caching
// network requests with service workers,
// mainly to make PWAs work offline.
// You can give it any value you want in this case.
const FAKE_ENDPOINT = "/fake-endpoint";
const saveToken = async (token: string) => {
try {
const cache = await caches.open(CACHE_NAME);
const responseBody = JSON.stringify({
[TOKEN_KEY]: token
});
const response = new Response(responseBody);
await cache.put(FAKE_ENDPOINT, response);
console.log("Token saved! 🎉");
} catch (error) {
// It's up to you how you resolve the error
console.log("saveToken error:", { error });
}
};
const getToken = async () => {
try {
const cache = await caches.open(CACHE_NAME);
const response = await cache.match(FAKE_ENDPOINT);
if (!response) {
return null;
}
const responseBody = await response.json();
return responseBody[TOKEN_KEY];
} catch (error) {
// Gotta catch 'em all
console.log("getToken error:", { error });
}
};
const displayCachedToken = async () => {
const cachedToken = await getToken();
console.log({ cachedToken });
};
// Uncomment the line below to save the fake token
// saveToken(FAKE_TOKEN);
displayCachedToken();
Without success means no result, i've tried to set data in safari and get them in standalone pwa
I need help with using sharp, I want my images to resize when uploaded but I can't seem to get this right.
router.post("/", upload.single("image"), async (req, res) => {
const { filename: image } = req.file;
await sharp(req.file.path)
.resize(300, 200)
.jpeg({ quality: 50 })
.toFile(path.resolve(req.file.destination, "resized", image));
fs.unlinkSync(req.file.path);
res.send("sent");
});
As I know you should pass a Buffer to sharp not the path.
Instead of resizing saved image, resize it before save. to implement this, you should use multer.memoryStorage() as storage.
const multer = require('multer');
const sharp = require('sharp');
const storage = multer.memoryStorage();
const filter = (req, file, cb) => {
if (file.mimetype.split("/")[0] === 'image') {
cb(null, true);
} else {
cb(new Error("Only images are allowed!"));
}
};
exports.imageUploader = multer({
storage,
fileFilter: filter
});
app.post('/', imageUploader.single('photo'), async (req, res, next) => {
// req.file includes the buffer
// path: where to store resized photo
const path = `./public/img/${req.file.filename}`;
// toFile() method stores the image on disk
await sharp(req.file.buffer).resize(300, 300).toFile(path);
next();
});
I can't play Youtube videos with puppeteer. It looks like chromium does not support video playback. What should I do ?
Here's my code :
const puppeteer = require('/root/node_modules/puppeteer/');
(async function main() {
try {
const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox']
})
const page = await browser.newPage();
await page.goto('https://www.youtube.com/watch?v=WjOGhNDX51M');
await page.waitFor(8000);
await page.screenshot({
path: '/var/www/html/test/example.png'
});
await browser.close()
} catch (e) {
console.log("our error", e);
}
})();
Thank you!
The chromium that is shipped with puppeteer does not have the codecs required for licensing and size reasons.
You can hook pupeteer to a "real" chrome instance like this :
const browser = await puppeteer.launch({
executablePath: '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome',
headless:false,
defaultViewport:null,
devtools: true,
//args: ['--window-size=1920,1170','--window-position=0,0']
args: ["--window-size=1920,1080", "--window-position=1921,0"]
})
Note the executablePath option.
Your path may vary.
HTH