Java tutorial
//package com.java2s; /* * Copyright 2016 Dmitry Brant. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class Main { public static Bitmap loadMpoBitmapFromFile(File file, long offset, int maxWidth, int maxHeight) throws IOException { // First, decode the width and height of the image, so that we know how much to scale // it down when loading it into our ImageView (so we don't need to do a huge allocation). BitmapFactory.Options opts = new BitmapFactory.Options(); InputStream fs = null; try { fs = new BufferedInputStream(new FileInputStream(file)); fs.skip(offset); opts.inJustDecodeBounds = true; BitmapFactory.decodeStream(fs, null, opts); } finally { if (fs != null) { try { fs.close(); } catch (IOException e) { // don't worry } } } int scale = 1; if (opts.outHeight > maxHeight || opts.outWidth > maxWidth) { scale = (int) Math.pow(2, (int) Math .round(Math.log(maxWidth / (double) Math.max(opts.outHeight, opts.outWidth)) / Math.log(0.5))); } if ((opts.outHeight <= 0) || (opts.outWidth <= 0)) { return null; } // Decode the image for real, but now with a sampleSize. // We have to reopen the file stream, and re-skip to the correct offset, since // FileInputStream doesn't support reset(). Bitmap bmp = null; fs = null; try { fs = new BufferedInputStream(new FileInputStream(file)); fs.skip(offset); BitmapFactory.Options opts2 = new BitmapFactory.Options(); opts2.inSampleSize = scale; bmp = BitmapFactory.decodeStream(fs, null, opts2); } finally { if (fs != null) { try { fs.close(); } catch (IOException e) { // don't worry } } } return bmp; } }