简体   繁体   English

在Android中从位图保存时如何设置dpi图像?

[英]How to set dpi image when saving it from bitmap in Android?

I use this function to save bitmap to file on sdcard:我使用此功能将位图保存到 sdcard 上的文件:

private static File storeImage(Context context, Bitmap image) {
    File pictureFile = getOutputMediaFile(context);
    if (pictureFile == null) {
        return null;
    }
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return pictureFile;
}

private static File getOutputMediaFile(Context context){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + context.getPackageName()
            + "/Files");

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
    File mediaFile;
    String mImageName="IMG_"+ timeStamp +".png";
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
    return mediaFile;
}

When I open the file and see image DPI information, it show 72 pixels/inch like this当我打开文件并查看图像 DPI 信息时,它像这样显示 72 像素/英寸

How can I set it to 300 pixels/inch, or something other value?如何将其设置为 300 像素/英寸或其他值?

Here is some helper methods I use for managing my screenshots and resizing of images.这是我用于管理屏幕截图和调整图像大小的一些辅助方法。

  public static Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight, boolean recycleOriginal) {
    int width = bm.getWidth();
    int height = bm.getHeight();

    // Determine scale to change size
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    // Create Matrix for maniuplating size
    Matrix matrix = new Matrix();
    // Set the Resize Scale for the Matrix
    matrix.postScale(scaleWidth, scaleHeight);

    //Create a new Bitmap from original using matrix and new width/height
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

    //Remove memory leaks if told to recycle, warning, if using original else where do not recycle it here
    if(recycleOriginal) {
        bm.recycle();

    }

    //Return the scaled new bitmap
    return resizedBitmap;

}
public static Bitmap cropImage(Bitmap imgToCrop, int startX, int startY, int width, int height, boolean recycleOriginal){
    Bitmap croppedImage = Bitmap.createBitmap(imgToCrop, startX, startY , width , height);

    if(recycleOriginal){
        imgToCrop.recycle();

    }

    return croppedImage;
}
public static Bitmap takeScreenshotOfView(Activity context, Bitmap.CompressFormat compressFormat){
    Bitmap screenshot = null;

    try {
        // create bitmap screen capture
        View v1 = context.getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        screenshot = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(context.getFilesDir() + File.separator + "A35_temp" + File.separator + "screenshot_temp");

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;

        screenshot.compress(compressFormat, quality, outputStream);
        outputStream.flush();
        outputStream.close();

    } catch (Throwable e) {
        // Several error may come out with file handling or OOM
        e.printStackTrace();
    }

    return screenshot;
}

These are all part of my ImageHelper class which I just use like:这些都是我的 ImageHelper 类的一部分,我只是使用它:

             Bitmap screenshot = ImageHelper.takeScreenshotOfView(this, Bitmap.CompressFormat.JPEG);
            Bitmap croppedImage = ImageHelper.cropImage(screenshot, ImageHelper.mStartXCrop, ImageHelper.mStartYCrop, ImageHelper.mCropWidth, ImageHelper.mCropHeight, true);
            returnImage =  ImageHelper.getResizedBitmap(croppedImage, mCropImageWidth, mCropImageHeight, false);

I don't think you are trying to screenshot, but you can still use the resize method.我认为您不是在尝试截图,但您仍然可以使用调整大小方法。

These are the methods which i used to set dpi to the bitmap while saving , refer here and also here .这些是我用来在保存时将dpi设置为位图的方法,请参阅此处此处

public void storeImage(Bitmap image) {
        try {
            File pictureFile = new File("yourpath");

            FileOutputStream fos = new FileOutputStream(pictureFile);


            ByteArrayOutputStream imageByteArray = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, imageByteArray);
            byte[] imageData = imageByteArray.toByteArray();

            //300 will be the dpi of the bitmap
            setDpi(imageData, 300);

            fos.write(imageData);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } 
    }


    public void setDpi(byte[] imageData, int dpi) {
        imageData[13] = 1;
        imageData[14] = (byte) (dpi >> 8);
        imageData[15] = (byte) (dpi & 0xff);
        imageData[16] = (byte) (dpi >> 8);
        imageData[17] = (byte) (dpi & 0xff);
    }

300 dpi is great for printing , so considering the pixel counts , when you set height and width (in inches) of image, multiply with 300. eg. 300 dpi 非常适合打印,因此考虑到像素数,当您设置图像的高度和宽度(以英寸为单位)时,乘以 300。例如。 lke on creating bitmap喜欢创建位图

Bitmap bm = Bitmap.createBitmap( W_inch*300  ,  H_inch*300  , Bitmap.Config.ARGB_8888);

it may not show 300dpi on image properties/details but the quality will be same as 300 dpi since DPI is dots per 1 inch line.它可能不会在图像属性/细节上显示 300dpi,但质量将与 300 dpi 相同,因为 DPI 是每 1 英寸线的点数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM