Determine If File Is an Image

determine if file is an image

Check the file for a known header. (Info from link also mentioned in this answer)

The first eight bytes of a PNG file always contain the following (decimal) values: 137 80 78 71 13 10 26 10

How can I determine if a file is an image file in .NET?

  1. You will only notice a performance hit from exceptions if you are constantly throwing them. So unless your program expects to see many invalid images (hundreds per second) you should not notice the overhead of exception handling.
  2. This is really the only way to tell if the image is a full image or corrupt. You can check the headers as the other people recommend, but that only checks to see if the beginning few bytes are correct, anything else could be garbage. Whether this is good enough or not depends on the requirements of your application. Just reading the header might be good enough for your use case.
  3. Yes, this is rather poor design on the BCL team's part. If you are loading many large images you very well could be hitting a real OOM situation in the large object heap. As far as I know, there is no way to differentiate the two exceptions.

Test if a file is an image file

This works pretty well for me. Hope I could help

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
class Untitled {
public static void main(String[] args) {
String filepath = "/the/file/path/image.jpg";
File f = new File(filepath);
String mimetype= new MimetypesFileTypeMap().getContentType(f);
String type = mimetype.split("/")[0];
if(type.equals("image"))
System.out.println("It's an image");
else
System.out.println("It's NOT an image");
}
}

How to check if a file is a valid image file?

A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above.

Good way to check if file extension is of an image or not

You could use .endsWith(ext). It's not a very secure method though: I could rename 'bla.jpg' to 'bla.png' and it would still be a jpg file.

public static bool HasImageExtension(this string source){
return (source.EndsWith(".png") || source.EndsWith(".jpg"));
}

This provides a more secure solution:

string InputSource = "mypic.png";
System.Drawing.Image imgInput = System.Drawing.Image.FromFile(InputSource);
Graphics gInput = Graphics.fromimage(imgInput);
Imaging.ImageFormat thisFormat = imgInput.rawformat;

How to check if image file is valid?

First of all, don't try to use System.Drawing in .NET Core applications. It's deprecated and works only on Windows anyway. The MSDN docs themselves suggest using ImageSharp or SkiaSharp instead.

Image files start with bytes that identify the file format. You'll have to read at least some of the file's contents to read image metadata like the image size, resolution etc. You can use ImageSharp's Identify method to read only the format and image properties, without loading the entire image.

You can read an uploaded file's contents using IFormFile.OpenReadStream.

using var stream=image.OpenReadStream();
try
{
var imageInfo=Image.Identify(stream, out var format);
if(imageInfo!=null)
{
var formatName=format.Name;
var width=imageInfo.Width;
var height=imageInfo.Height;
}
}
catch(InvalidImageContentException exc)
{
//Invalid content ?
}

The format parameter is an IImageFormat value that contains information about the image format, including its name and mime types.

The IImageInfo object returned contains the image dimensions, pixel type, resolution etc.

The method documentation explains that the return value will be null if no suitable decoder is found:

The IImageInfo or null if a suitable info detector is not found.

But an exception will be thrown if the content is invalid:

InvalidImageContentException Image contains invalid content.

Without testing this, I assume that a text file will result in a null but a file with just a GIF header without valid content will result in an exception.

You can use ImageSharp to resize the image or convert it to another format. In that case it's not enough to just load the metadata. You can use Load to load the image from the stream, detect its format and then manipulate it.

using var stream=image.OpenReadStream();
var image=Image.Load(stream, out var format);

var formatName=format.Name;
if (notOk(formatName,image.Height,image.Width))
{
using var outStream=new MemoryStream();
image.Mutate(x => x.Resize(desiredWidth, desiredHeight));
image.SaveAsPng(outStream);
outStream.Position=0;
//Store the contents of `outStream`
}

How to check if a file is a valid image?

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\r\n\x1a\n": "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 ""
}

How to check if the file is an image

According to the Javadocs, read returns null if the file can not be read as an image.

If no registered ImageReader claims to be able to read the resulting
stream, null is returned.

So, your code should be the following:

try {
Image image = ImageIO.read(new File(name));
if (image == null) {
valid = false;
System.out.println("The file"+name+"could not be opened , it is not an image");
}
} catch(IOException ex) {
valid = false;
System.out.println("The file"+name+"could not be opened , an error occurred.");
}

Android: How to check if file is image?

Try this code.

public class ImageFileFilter implements FileFilter {

private final String[] okFileExtensions = new String[] {
"jpg",
"png",
"gif",
"jpeg"
};

public boolean accept(File file) {
for (String extension: okFileExtensions) {
if (file.getName().toLowerCase().endsWith(extension)) {
return true;
}
}
return false;
}

}

It'll work fine.

Use this like
new ImageFileFilter(pass file name);

How can I check if a file is an image file without checking the path extension?

UIImage *image = [UIImage imageNamed:@"SomeFile.xyz"];
if (image == nil) {
NSLog(@"This is probably text file");
}

If image is nil means the file may be text or another type of file.



Related Topics



Leave a reply



Submit