Python / base64 === ###### tags: `Python` ###### tags: `Python`, `PyPi`, `base64`, `b64encode`, `decode`, `buffered image`, `image file`, `MIME`, `JPG`, `JPEG` <br> [TOC] <br> ## image: from file ```python= def image_to_base64(image_path: Path): ''' Function to read an image and convert it to a Base64 string ''' with open(image_path, "rb") as image_file: encoded_string = base64.b64encode( image_file.read()).decode("utf-8") return encoded_string ``` - ### 透過程式產生 1024x768 空白影像 ```python= from PIL import Image # Define the image dimensions width, height = 1024, 768 color = (255, 255, 255) # White color # Create a new blank white image image = Image.new("RGB", (width, height), color) # Save the image as 1024x768.jpg image_path = "1024x768.jpg" image.save(image_path) ``` <br> ## image: from buffered ```python= import base64 from io import BytesIO # Create a new blank white image image = Image.new("RGB", (width, height), color) # Save the image to a BytesIO object buffered = BytesIO() image.save(buffered, format="JPEG") # Encode the image in base64 encoded_image = base64.b64encode(buffered.getvalue()).decode('utf-8') # Construct the base64 string with the correct prefix for JPEG base64_image_string = f"data:image/jpeg;base64,{encoded_image}" base64_image_string[:100] # Output only the first 100 characters for brevity ``` 執行結果: ``` 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aH' ``` <br> ## 討論 ### image.save(format="JPEG"): JPG vs JPEG - ### Question `image.save(buffered, format="JPEG")` 中,只能使用 JPEG, 不能用 JPG? - ### gpt-4o-2024-08-06 (round-1) In the context of base64 encoding, the MIME type for JPEG images is officially `"image/jpeg"`, regardless of whether the file extension is `.jpg` or `.jpeg`. The two extensions are interchangeable in practice, but for the base64 string, only `"image/jpeg"` is valid according to the standard. Even if the image file has a `.jpg` extension, the correct prefix remains: ``` data:image/jpeg;base64, ``` So, you should always use `"image/jpeg"` in the base64 string, even if the original file extension is `.jpg`. - ### gpt-4o-2024-08-06 (round-2) 在 `image.save(buffered, format="JPEG")` 中,這裡的 `format="JPEG` 是正確的,因為在內部,這個格式的標準名稱就是 `JPEG`。雖然檔案副檔名可以是 .jpg 或 .jpeg,但它們本質上是相同的格式。早期因為檔案命名的限制,才有 .jpg 這個縮短版本。 PIL(Python Imaging Library)只認識 `JPEG` 作為有效的格式,因此在 `image.save()` 方法中無法使用 `JPG`,你必須使用 `JPEG`。 簡而言之,即使副檔名是 .jpg,在 `image.save()` 方法中還是應該使用 `JPEG`。 <br> ### mimetype: JPG vs JPEG - ### Question data:image/jpeg;base64, data:image/jpg;base64, 可以互用嗎? - ### gpt-4o-2024-08-06 在技術上,data:image/jpeg;base64, 和 data:image/jpg;base64, 是可以互用的,因為它們都指向相同的 JPEG 格式。瀏覽器和大多數應用程式通常都能夠理解兩者,並正確處理影像資料。 然而,根據 MIME 標準,官方正確的類型是 **image/jpeg**。**image/jpg** 並不是正式的 MIME 類型,但因為 .jpg 是常用的副檔名,許多系統仍能處理 image/jpg。 為了保持一致性和標準性,建議使用 **image/jpeg**。但在實際應用中,大多數情況下,兩者可以互換使用。