To check if a downloaded JPEG image is readable and not corrupted in Ruby, you can use the jpeginfo
gem. First, install the gem by adding it to your Gemfile:
rubygem 'jpeginfo'
Then, run bundle install
to install the gem. After that, you can use the following code to check if the downloaded JPEG image is readable:
rubyrequire 'open-uri'
require 'jpeginfo'
def image_readable?(url)
image = open(url)
jpeginfo = JpegInfo.new(image)
jpeginfo.valid?
rescue StandardError => e
puts "Error checking image readability: #{e.message}"
false
ensure
image&.close
end
url = 'https://example.com/image.jpg'
if image_readable?(url)
puts "The image at #{url} is readable."
else
puts "The image at #{url} is corrupted or unreadable."
end
This code defines a method image_readable?
that takes a URL to a JPEG image, opens the image using open-uri
, and then uses JpegInfo
from the jpeginfo
gem to check if the image is valid. If the image is readable, image_readable?
returns true
; otherwise, it returns false
.
المزيد من المعلومات
بالتأكيد! لفحص ملف صورة JPEG والتحقق من أنه قابل للقراءة وليس تالفًا، يمكنك استخدام الأمثلة التالية:
-
استخدام مكتبة MiniMagick:
تستطيع استخدام مكتبة MiniMagick لفحص صحة الملفات الصورة. يجب أولاً تثبيت MiniMagick بإضافتها إلى ملف Gemfile:rubygem 'mini_magick'
ثم قم بتشغيل
bundle install
لتثبيت المكتبة. بعد ذلك، يمكنك استخدام الكود التالي لفحص الصورة:rubyrequire 'mini_magick' def image_readable?(url) image = MiniMagick::Image.open(url) image.valid? rescue MiniMagick::Invalid false end url = 'https://example.com/image.jpg' if image_readable?(url) puts "الصورة في #{url} قابلة للقراءة." else puts "الصورة في #{url} تالفة أو غير قابلة للقراءة." end
-
استخدام مكتبة
fastimage
:
يمكنك أيضًا استخدام مكتبةfastimage
للتحقق من صحة ملفات الصور JPEG وغيرها. يمكنك تثبيت المكتبة عبر إضافتها إلى ملف Gemfile:rubygem 'fastimage'
ثم قم بتشغيل
bundle install
لتثبيت المكتبة. يمكنك استخدام الكود التالي لفحص الصورة:rubyrequire 'fastimage' def image_readable?(url) FastImage.size(url) != nil rescue FastImage::ImageFetchFailure false end url = 'https://example.com/image.jpg' if image_readable?(url) puts "الصورة في #{url} قابلة للقراءة." else puts "الصورة في #{url} تالفة أو غير قابلة للقراءة." end
تذكر أنه في بعض الحالات، قد لا تكون هذه الطرق كافية للتحقق الدقيق من صحة الصورة بنسبة 100٪، ولكنها تقدم طرقًا بسيطة للتحقق من القدرة على قراءة الملف.