doushaqing7080 2014-09-21 12:52
浏览 147
已采纳

如何检查文件是否为有效图像?

I am building a web application.

On one of the pages there is an upload form, where user can upload a file. After the upload is done, I want to check on the server if the uploaded file is an image.

Is it possible to check this beyond simple file extension checking (i.e. not assuming that a *.png filename is actually a PNG image)?

For example, if I edit a JPEG image adding/editing a byte in a random place to make an invalid JPEG file, I want to detect that it is not a JPEG image anymore. I used to do such type of thing via PHP some time ago, using a GD library.

I would like to know if it is possible to do with Go?

  • 写回答

3条回答 默认 最新

  • douchuza8908 2014-09-21 13:08
    关注

    What is usually done is checking if the file has the right magic number for the image file format you want. While this test is not super accurate, it is usually good enough. You can use code like this:

    package foo
    
    import "strings"
    
    // image formats and magic numbers
    var magicTable = map[string]string{
        "\xff\xd8\xff":      "image/jpeg",
        "\x89PNG
    \x1a
    ": "image/png",
        "GIF87a":            "image/gif",
        "GIF89a":            "image/gif",
    }
    
    // mimeFromIncipit returns the mime type of an image file from its first few
    // bytes or the empty string if the file does not look like a known file type
    func mimeFromIncipit(incipit []byte) string {
        incipitStr := []byte(incipit)
        for magic, mime := range magicTable {
            if strings.HasPrefix(incipitStr, magic) {
                return mime
            }
        }
    
        return ""
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?