I see no reason why Python libraries can not be called from Scratch files.
Let me try using my existing Scratch.py (https://hodentekhelp.blogspot.com/2024/06/what-is-scratch-file-in-pycharm.html) to call the PIL library.
You see you can do it.
However, you see an indent error. This is not a serious error. It just says there is an unexpected indent. You can get rid of this error by moving the line "from PIL import Image" back one step, by removing the white space before "from".
This brings another weak warning (Yellow upright triangle with a ! inside). This is a weak warning and not an error. The call statement should be the first statement.
Now remove the print("Scratchy". This clears the weak warning.
Now that the calling of Image is successful, let us explore Image a little bit.
Using Image
The PyCharm provides a drop-down for facilitating code and you should watch out.
Let me see if I can Open an image on my desktop (C:\Users\hoden\OneDrive\Desktop\Beware.jpg).
To open an image you would use the open() method. You should use the image path as an argument in open().
The image we are using Beware.jpg is on the desktop and its location is
"C:\Users\hoden\OneDrive\Desktop\Beware.jpg"
You get a bunch of errors for each "/" in the path. This needs to be corrected. The next image file specification removes the bunch of indent errors.
The code runs without errors. To see the image, we need to call another library. For now, since we have image, let me get the width and height of the image by the following code (you need not display the image to get its properties):
=========================================================
from PIL import Image
image_path = "C://Users//hoden//OneDrive//Desktop//Beware.jpg"
image=Image.open(image_path)
width, height = image.size
print(f"Image dimensions: Width = {width}, Height = {height}")
==========================================================
This code runs as well and you get the Height and width as,
Height= 259 Width= 259
The units are in pixels.
The height and width of the image from its properties using Windows explorer is shown here.
Important thing to note:
File references may sometime gets tricky as the file may be on the desktop, or some other location. It is best to catch an error, if the file is not at the expected location.
No comments:
Post a Comment