How to Check If the File Is Image

How to check if a file is a valid image?

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");
}
}

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);

PHP check if file is an image

Native way to get the mimetype:

For PHP < 5.3 use mime_content_type()

For PHP >= 5.3 use finfo_open() or mime_content_type()

Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

While mime_content_type is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).

If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

function getMimeType($filename)
{
$mimetype = false;
if(function_exists('finfo_open')) {
// open with FileInfo
} elseif(function_exists('getimagesize')) {
// open with GD
} elseif(function_exists('exif_imagetype')) {
// open with EXIF
} elseif(function_exists('mime_content_type')) {
$mimetype = mime_content_type($filename);
}
return $mimetype;
}

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 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.

Error: Main method not found in class inter333, please define the main method as: public static void main(String[] args)

You need to actually call your readFiles() method from the main class to start it and also move your class variables to be under your class declaration.

public class inter333 {

List<String> SampleStringA = new ArrayList<String>();
List<String> SampleStringB = new ArrayList<String>();
File SampleStringAFile = new File("C:\\Users\\Trapper\\Desktop\\SampleStrings1ma.txt");
File SampleStringBFile = new File("C:\\Users\\Trapper\\Desktop\\SampleStrings1mb.txt");
BufferedReader reader = null;

public static void main(String[] args) {
readFiles();
}

/*Other methods*/
}


Related Topics



Leave a reply



Submit