Java 裁剪具有预设纵横比和宽度/高度的图像并保存

Java 裁剪具有预设纵横比和宽度/高度的图像并保存,java,android,image,crop,Java,Android,Image,Crop,我已经建立了一个相机应用程序,可以让我拍照,但我想用一个特定的(预设)宽度/高度和纵横比来保存它 例如: 红色:旧图片(来源) 绿色:新图片 在红色和绿色之间:边距 我尝试了以下方法(运气不佳): 我尝试用边距在左侧(第一个边距)和顶部(第二个边距)切割特定数量的像素,在总宽度和高度上切割相同数量的像素。不工作 Github上也有一些可用的库,但它们都允许我选择一个图像并对其进行编辑-我不需要手动编辑,我希望有预设的边距进行裁剪 此外,这里关于堆栈溢出的可能解决方案,以及仅仅通过谷

我已经建立了一个相机应用程序,可以让我拍照,但我想用一个特定的(预设)宽度/高度和纵横比来保存它

例如:

  • 红色:旧图片(来源)
  • 绿色:新图片
  • 在红色和绿色之间:边距
我尝试了以下方法(运气不佳):

我尝试用边距在左侧(第一个边距)和顶部(第二个边距)切割特定数量的像素,在总宽度和高度上切割相同数量的像素。不工作

Github上也有一些可用的库,但它们都允许我选择一个图像并对其进行编辑-我不需要手动编辑,我希望有预设的边距进行裁剪

此外,这里关于堆栈溢出的可能解决方案,以及仅仅通过谷歌搜索或查找教程,都不会给我带来任何运气。 搜索查询:

java android裁剪图像

java android裁剪图像教程


谁能帮我?

我也快到了。挣扎了几个星期,但我的大脑变得清晰起来:一切正常,但我没有将图片/图像保存到设备上

利润在起作用

明天将使用我找到的解决方案更新/编辑此帖子

更新:

    // get String with path to file from other activity and make new File of it
    File editPhotoFile = new File(globalFileString);
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath(), bmOptions);

    // crop the bitmap with new margins: bitmap, left, top, width, height
    Bitmap croppedBmp = Bitmap.createBitmap(bitmap, marginLeft, marginTop, bitmapHeight, bitmapWidth);

    // save bitmap to new file
    FileOutputStream out = null;
    File mediaFile;
    try {
        mediaFile = new File(globalFileString);
        out = new FileOutputStream(mediaFile);
        croppedBmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

因此,您不希望用户编辑图像croping..部分?不。我想自己裁剪图像,这样图像在每个设备上具有相同的比率。一些设备具有3:4传感器,其他设备具有9:16或16:9传感器,依此类推。这就是原因。
    // get String with path to file from other activity and make new File of it
    File editPhotoFile = new File(globalFileString);
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath(), bmOptions);

    // crop the bitmap with new margins: bitmap, left, top, width, height
    Bitmap croppedBmp = Bitmap.createBitmap(bitmap, marginLeft, marginTop, bitmapHeight, bitmapWidth);

    // save bitmap to new file
    FileOutputStream out = null;
    File mediaFile;
    try {
        mediaFile = new File(globalFileString);
        out = new FileOutputStream(mediaFile);
        croppedBmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }