动态加载jpg文件

时间:2014-10-11 00:25:22

标签: android bitmap drawable

我想在图像视图中加载基于我按顺序读取的txt文件的不同jpg文件。我把jpg文件放在资产中。 我找到了以下代码:

((ImageView)view).setImageBitmap(BitmapFactory.decodeFile("/data/data/com.myapp/files/someimage.jpg"));

我试图插入:

(GetApplicationContext().getResources().getAssets()+"file.jpg")

知道我使用android studio的建议是什么:

  1. 如何找到我的“资产”路径

  2. 是否应该使用资产目录

  3. 有关其他方法的任何建议

  4. 目录系统在android上一点也不容易!

2 个答案:

答案 0 :(得分:0)

如果要在资源目录中加载图像,可以这样做,

InputStream is = context.getAssets().open(imageFileName);
Bitmap bitmap = BitmapFactory.decodeStream(is);

OR

将图像放在可绘制的目录中,然后将它们用作资源。

int drawableId = context.getResources().getIdentifier("fileNameWithoutExtension", "drawable", context.getPackageName();
Drawable drawable = context.getResource().getDrawable(drawableId);

答案 1 :(得分:0)

再次感谢您的帮助!非常感谢!

代码:

public class MyActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           drawJPG();
        }
    });

}

private void drawJPG() {
    Context context = null;
    InputStream is = null;
    context = getApplicationContext();
    try {
        is = context.getAssets().open("myjpg.jpg");
    } catch (IOException e) {
        e.printStackTrace();
    }
    Bitmap bitmap = BitmapFactory.decodeStream(is);
}

调试它在bitmap()

看起来很好
this = {android.graphics.Bitmap@830031440008}
nativeBitmap = 2052352744
buffer = {byte[201300]@830031238688}
width = 275
height = 183
density = -1
isMutable = false
isPremultiplied = true
ninePatchChunk = null
layoutBounds = null

选项2:

public class MyActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           drawJPG();
        }
    });

}

private void drawJPG() {
    Context context = null;
    context = getApplicationContext();
    int drawableID = context.getResources().getIdentifier("myjpg", "drawable", context.getPackageName());
    Drawable drawable = context.getResources().getDrawable(drawableID);

}

通过调试看起来仍然可以:

this = {android.content.res.Resources@830030928528}
value = {android.util.TypedValue@830030928808}"TypedValue{t=0x3/d=0x3 "res/drawable-hdpi-v4/myjpg.jpg" a=4 r=0x7f020000}"
id = 2130837504
isColorDrawable = false
key = 17179869187
cs = null
dr = null
file = {java.lang.String@830031232520}"res/drawable-hdpi-v4/myjpg.jpg"