给定文件路径(没有扩展名)我想知道文件中的图像是JPEG还是PNG。
我该怎么做?
答案 0 :(得分:8)
尝试查找图片标题,有点像这样:
File file = /* (get your file) */;
byte[] data = new byte[2];
try {
new FileInputStream(file).read(data);
} catch (Exception e) {
// handle the error somehow!
}
if (data[0] == 0xFF && data[1] == 0xD8) {
// jpeg
} else if (data[0] == 0x89 && data[1] == 0x50) {
// png
} else {
// error?
}
JPEG headers will always be FFD8
和PNG headers are 89504E470D0A1E0A
(我们只需要查看前两个字节以区分JPEG)。
答案 1 :(得分:2)
你可以这样找到:
第1步:你只得到图像边界....
第2步:您可以使用以下方法更改相应尺寸的图像
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
in.mark(in.available());
BitmapFactory.decodeStream(in, null, options);
(or)
BitmapFactory.decodeFile(pathName);
(or)
BitmapFactory.decodeResource(MainActivity.this.getResources(), R.drawable.ic_launcher);
String name = options.outMimeType;
以下方法用于高效地加载大位图 使用所需的高度和宽度重新调整图像大小
public static Bitmap decodeSampledBitmapFromResource(InputStream in,
int reqWidth, int reqHeight) throws IOException {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
in.mark(in.available());
BitmapFactory.decodeStream(in, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
in.reset();
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(in, null, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
答案 2 :(得分:1)
你搜索这个吗?为什么你没有扩展名呢?
"在Java 7中,您现在可以使用
Files.probeContentType(path)"
-> source 但我们不确定它是否支持android。
那么为什么不直接获取完整路径并使用子字符串提取文件扩展名?