使用先前存储的位图中像素数的两倍创建新的位图

时间:2016-11-23 12:32:57

标签: java android image android-studio bitmap

首先,我从图库中选取一个图像并将其转换为位图。

我想要实现的是,当按下某个按钮时,会创建一个新位图,其中先前存储的位图中的像素数量加倍。接下来,原始位图中的每个像素应存储在新位图中相同坐标周围的四个像素中。

我已经尝试循环遍历这两个位图,但是我收到的错误是 Y应该是> BITMAP.HEIGHT()

不确定我在这里弄错了什么。

即使我在循环中修复了这个错误,UI线程是否可以设法循环遍历大量像素而不会无响应?

MainActivity代码粘贴在下面:

公共类MainActivity扩展了AppCompatActivity {

static final int PICK_IMAGE = 11;

ImageView image;

Bitmap bmp;

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

    Button chooseImage = (Button) findViewById(R.id.choose_btn);
    Button apply = (Button) findViewById(R.id.apply_btn);
    image = (ImageView) findViewById(R.id.image_view);

    chooseImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
        }
    });

    apply.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int viewHeight = image.getHeight();
            int viewWidth = image.getWidth();

            int bmpHeight = bmp.getHeight();
            int bmpWidth = bmp.getWidth();

            Bitmap betterQuality = Bitmap.createBitmap(bmpWidth*2, bmpHeight*2, Bitmap.Config.ARGB_8888);

            int newXVal = 0, newYVal = 0, limX = 2, limY = 2;
            int color;
            for (int x = 0; x < bmpWidth; x++) {
                for (int y = 0; y < bmpHeight; y++) {
                    for (int a = newXVal; a < limX; a++) {
                        for (int b = newYVal; b < limY; b++) {
                            color = bmp.getPixel(x, y);
                            betterQuality.setPixel(a, b, Color.argb(Color.alpha(color), Color.red(color), Color.blue(color), Color.green(color)));
                        }
                    }
                    newXVal++;
                    newYVal++;
                    limX++;
                    limY++;
                }
            }
            image.setImageBitmap(betterQuality);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE && resultCode == RESULT_OK){
        Uri selectedImage = data.getData();
        try {
            bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage));
            image.setImageBitmap(bmp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

}

0 个答案:

没有答案