检查文件是否为图片

Check if file is an image

我构建了一种从文件向卡片添加图像并将其存储在自定义 属性 中的方法。这很好用。

 answer file tImageDialogTranslations with type "Images|jpg|jpeg|png"
 if  it is not empty then
  put  it into tMyImagePath

  put url("binfile:" & tMyImagePath) into tMyImage
  put base64encode( tMyImage) into tBase64ImgData

  # store image in cust prop
  set the cImageBlob of img "img_collection_picture" to  tBase64ImgData 

  #show image
  put base64decode(tBase64ImgData) into tShowImage
  set the text of image "img_collection_picture" to tShowImage
 end if

遗憾的是,当我在文件答案对话框中添加 * 时,我还可以选择另一种文件类型,例如 txt,然后存储在自定义 属性 中,但不会显示在图片。

如何检查用户是否真的选择了有效的图像文件?

我认为您可以通过检查文件扩展名或文件的幻数来验证。这些信息可以帮助您确定该文件是否为图像文件。扫描文件内容以验证它是否是图像文件不是一个好主意。

我弄明白了,我想我会分享整个相关部分:

answer file tImageDialogTranslations with type "Images|jpg,jpeg,png,gif"
if it is not empty then
  put  it into tMyImagePath
  put url("binfile:" & tMyImagePath) into tMyImage
  put binarydecode("H8",tMyImage,tMyImageHex) -- to check if it is actually an image
  put base64encode( tMyImage) into tBase64ImgData


  set the itemdel to comma
    if tMyImageHex is among the items of "ffd8ffe0,47494638,89504e47"  then

     ### store image in custom property
     set the cImageBlob of img "img_collection_picture" to  tBase64ImgData 

     ### now display image in field
     put base64decode(tBase64ImgData) into tShowImage
     set the text of image "img_collection_picture" to tShowImage

    else
     # do nothing / error 100499
     answer "Error 100499: Please choose an image file. "
    end if

 else
     # do nothing since no file was chosen
 end if