This is the 24th day of my participation in Gwen Challenge

Today, I wanted to change the desktop wallpaper, but I didn’t find a suitable one. Later, when I was staring at the lock screen of the computer in a daze, I suddenly felt that the lock screen pictures were quite attractive, so I had the idea of writing a program to save the lock screen pictures every day as the desktop wallpaper. Also associated with the bing search background image, is also quite good, together to achieve it.

Save the Microsoft lock screen background

First of all, I found the file path of Microsoft lock screen pictures. After a simple query, I found it was in this folder:

C:\Users\LvLin\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets
Copy the code

This is my local path, and it’s going to be different because everyone has a different username, so be aware of that. In addition, these image files do not have a suffix by default, we can add a picture format suffix to a few of them to see the effect:

You can see that each picture is divided into landscape and portrait two specifications, in the implementation of the time we only want to landscape specifications of the picture.

A quick overview of the code logic to implement:

  1. Read all files under the lock screen picture directory;
  2. Screen pictures of horizontal screen size;
  3. Add the corresponding suffix name and save it in the target folder.

Then dry. Create project folder getImg and initialize the project:

> npm init -y
Copy the code

Create an IMG folder to store images. The object code is written in the getimgfromlscreen.js file.

First install a NPM package, used to judge the width and height of the picture, to achieve the image specification screening:

> npm i --save image-size
Copy the code

The code for getimgfromlscreen.js looks like this:

// 1. Read all files in Microsoft lock screen picture directory;
// 2. Select a horizontal screen image;
// 3. Add the corresponding suffix and save the file to the target folder.
const fs = require('fs/promises');
const sizeOf = require('image-size');
var os = require('os');

const username = os.userInfo().username; // Get the user name
const LScreenFilePath = `C:\\Users\\${username}\\AppData\\Local\\Packages\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\LocalState\\Assets\\`;

/ * * * *@param {String} SavePath The target storage path. The default is the IMG folder under the project. You can transfer an absolute path *@param {String} FilePath Microsoft lock screen picture directory, The default is C: \ Users \ username \ % % AppData \ Local \ Packages \ Microsoft Windows. ContentDeliveryManager_cw5n1h2txyewy \ LocalState \ Assets \ * /
async function getImgFromLScreen(savePath = '.\\img\\', filePath = LScreenFilePath) {
    try {
        // Get a list of all the files in the folder
        let dir = await fs.readdir(filePath);
        let dimensions, fileName;
        
        // Loop through the list of files to filter specifications
        for (let i = 0; i < dir.length; i++) {
            fileName = dir[i];
            dimensions = sizeOf(filePath + fileName);

            // Screen out landscape images by the ratio of width and height
            if (dimensions.width > dimensions.height) {
                // Copy the image to the destination pathsaveImg(filePath, fileName, savePath, dimensions.type); }}}catch (err) {
        console.error(err.message); }}/** * copy the image to the destination path **@param {String} FilePath Path of the screen-lock file *@param {String} FileName Specifies the name of the screen lock background file *@param {String} SavePath Target path *@param {String} ImgType Lock screen background image format, used to add file name extensions */
function saveImg(filePath, fileName, savePath, imgType) {
    try {
        fs.copyFile(filePath + fileName, savePath + fileName +'. '+ imgType);
    } catch (error) {
        console.error(err.message); }}// Export the module
module.exports = getImgFromLScreen;
Copy the code

Create an index.js entry file and execute the module code:

const getImgFromLScreen = require('./getImgFromLScreen');

getImgFromLScreen();
Copy the code

Run index.js to see the result:

> node index.js
Copy the code

nice!!!

Get the Bing search background image

Now let’s look at how to get Beijing pictures from Bing search.

Open the bing search page, through the Network panel, you can see the image path interface, remove some environmental related parameters, the interface path for https://cn.bing.com/HPImageArchive.aspx?format=js&n=1, access to the data format is as follows:

{
    "images": [{..."url": "/th? id=OHR.DenaliCaribou_ZH-CN9804350098_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp". }]."tooltips": {... }}Copy the code

https://cn.bing.com is the image path we need in images.url Mosaic, change 1920×1080 into UHD, remove the parameter behind?, and you can get the hd background image address.

Here’s a quick rundown of the code logic that gets the Bing search background image:

  1. Access bing related interface to obtain the relative path of the picture;
  2. Splicing out the access path of the picture according to the rules;
  3. Access to get images and store them in the target folder.

Add a file getimgfrombiying.js to the project, with the following contents and explanations:

// Get the background image of Bing by sending a request and save it in a local folder
// Take a parameter as the path to save the image. The default is C:\image
/ / use bing official interface at https://cn.bing.com/HPImageArchive.aspx?format=js&n=1

const https = require('https');
const fs = require('fs');

/** * 1. Access the relevant interface of Bing to obtain the relative path of the image; * 2. Splice the access path of the picture according to the rules; * 3. Access the image and store it in the target folder. * *@param {String} filePath 
 */
function getImgFromBiYing(filePath = '.\\img\\') {
    const options = {
        hostname: 'cn.bing.com'.port: 443.path: '/HPImageArchive.aspx? format=js&n=1'.method: 'GET'
    };

    // Request the interface to obtain the image path information
    const req = https.request(options, res= > {
        res.on('data'.data= > {
            try {
                let obj = JSON.parse(data.toString());
                let url = obj.images[0].url;
                // Change the image path to hd size and remove unnecessary parameters
                let imgUrl = url.split('&') [0].replace('1920x1080'.'UHD');
                // Get the image file name
                let fileName = imgUrl.replace('/th? id='.' ');

                // Get the image resource and save the image
                saveImg(imgUrl, filePath + fileName);
            } catch(error) { process.stdout.write(error); }}); }); req.on('error'.error= > {
        console.error(error);
    });

    req.end();
}

/** * Store the image to the target folder **@param {String} path 
 * @param {String} fileName 
 */
function saveImg(path, fileName) {
    const options = {
        hostname: 'cn.bing.com'.port: 443,
        path,
        method: 'GET'
    };

    const req = https.request(options, res= > {
        let imgData = ' ';
        res.setEncoding("binary");
        ImgData // request image resources and store them in imgData
        res.on('data'.chunk= > {
            imgData += chunk;
        });

        res.on('end'.() = > {
            try {
                // Write the image to the destination folder
                fs.writeFile(fileName, imgData, 'binary'.err= > {
                    if (err) {
                        console.error(err.message)
                        return}})}catch (error) {
                console.error(error.message); }})}); req.on('error'.error= > {
        console.error(error.message);
    });

    req.end();
}

// Export the module
module.exports = getImgFromBiYing;
Copy the code

Modify the index.js file:

const getImgFromLScreen = require('./getImgFromLScreen');
const getImgFromBiYing = require('./getImgFromBiYing');

getImgFromBiYing();
getImgFromLScreen();
Copy the code

Run index.js to view the image.

Background configuration

The index.js file is processed so that the program can run once a day and automatically pull new files.

const getImgFromLScreen = require('./getImgFromLScreen');
const getImgFromBiYing = require('./getImgFromBiYing');

// Pull every 12 hours
setInterval(() = >{
    getImgFromBiYing();
    getImgFromLScreen();
    console.log(new Date() + ': Pulled the latest Bing background and Microsoft lock screen')},12*3600*1000)
Copy the code

Finally, go to Windows Personalization, set the folder for storing images to our background image directory, and select Slide show mode.

Switch your desktop wallpaper dynamically every day

The last

Is there any place that can continue to be optimized? Please let us know your thoughts in the comments section

If you think the article is good, please praise ~