gpt4 book ai didi

java - 从canvas java创建位图

转载 作者:行者123 更新时间:2023-12-01 19:04:07 26 4
gpt4 key购买 nike

解决方案

感谢 @ChandraSekhar 的建议,问题是我将不可变位图传递给 Canvas 构造函数。解决方案是在使用 BitmapFactory.decodeFile(); 时创建它的副本;

Bitmap bmp = BitmapFactory.decodeFile(imageURL).copy(Bitmap.Config.ARGB_8888, true);

所以我有一个位图,我正在使用 bitmapFactory.decodeFile() ,这可以工作。我能够创建位图,然后我需要创建 Canvas ,这就是事情变得奇怪的地方。

这是正在发生的事情的流程。我捕获一个图像,然后将其传递给 functionA 来调整其大小,并将其保存并返回其文件路径。 (我正在使用 Phonegap Cordova)

然后我将该 URL 传递回我的 java 并使用之前保存的图像并在 functionB 中对其进行操作

有问题的代码:

// GET URL TO IMAGE
final JSONObject options = optionsArr.optJSONObject(0);
String imageURL = options.optString("image");

// create image bitmap
Bitmap bmp = BitmapFactory.decodeFile(imageURL);
bmp = Bitmap.createBitmap(bmp,0,0,655,655);

/* Everything works fine until this point */

// create image canvas
Canvas canvas = new Canvas(bmp);
Bitmap one = Bitmap.createBitmap(bmp);
canvas.drawBitmap(one,0,0,null);

我没有收到任何错误,它只是挂起。这是最令人兴奋的 - 如果我运行另一个函数,首先说 functionB ,其中一个可以工作,但另一个不能。

我想也许我需要刷新并关闭我的第一个 FileOutputStream,但这似乎没有任何效果。我已经为所有元素、位图、 Canvas 和文件输出流尝试了不同的变量名称。

这是完整功能的示例...注意:因为我使用的是phonegap/cordova,所以我返回一个字符串

public String none(JSONArray optionsArr) {

// SET FILE PATH
String filePath = "";
File path = new File(Environment.getExternalStorageDirectory()+"/myApp/");

// TMP.jpg is where we store our temporary version of the image
File NewFilePath = new File(path, "tmp_NBB.jpg");

// CREATE FOLDERS IF NEEDED
try{
boolean success = false;

if(!path.exists()){
success = path.mkdir();
}
if (!success){
Log.d("NONE","Folder not created.");
}
else{
Log.d("NONE","Folder created!");
}
}
catch (Exception e){
e.printStackTrace();
}
// GET URL TO IMAGE
final JSONObject options = optionsArr.optJSONObject(0);
String imageURL = options.optString("image");

// create image bitmap
Bitmap bmp = BitmapFactory.decodeFile(imageURL);
bmp = Bitmap.createBitmap(bmp,0,0,655,655);

// create image canvas
Canvas canvas = new Canvas(bmp);
Bitmap none = Bitmap.createBitmap(bmp);
canvas.drawBitmap(none,0,0,null);

// SAVE IMAGE
try {
// OUTPUT STREAM
FileOutputStream out = new FileOutputStream(NewFilePath);
none.compress(Bitmap.CompressFormat.JPEG, 100, out);

// GET FILE PATH
Uri uri = Uri.fromFile(NewFilePath);
filePath = uri.toString();

try{
out.flush();
out.close();

// RETURN FILE PATH
return filePath;
}
catch (Exception e){
e.printStackTrace();
}


} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}

就像我说的,这适用于第一个图像,但是当我尝试再次打开该图像时,根据返回的文件路径,它会在创建 Canvas 行处分块。

编辑:我正在使用的图像路径如下所示:/mtn/sdcard/myApp/tmp.jpg想法?

最佳答案

Bitmap one = Bitmap.createBitmap(bmp);

在上面的代码中,bmp是一个位图,您正在从bmp创建另一个位图对象one

删除该行并尝试更改

canvas.drawBitmap(one,0,0,null);

canvas.drawBitmap(bmp,0,0,null);

关于java - 从canvas java创建位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10882164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com