I don't don't get any warning on eclipse when I compile this code, but when I run it on device or emulator, that program was forced to close.
public class MainActivity extends Activity {
ImageView img;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//convert imageview to bitmap
img =(ImageView) findViewById(R.id.imageView1);
BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
final Bitmap imgbitmap = drawable.getBitmap();
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//convert bitmap to grayscale
Bitmap imgnew;
imgnew = toGrayscale(imgbitmap);
//convert bitmap to imageview
ImageView imgbit;
imgbit = (ImageView) findViewById(R.id.imageView2);
imgbit.setImageBitmap(imgnew);
}
});
}
public Bitmap toGrayscale(Bitmap bmpOriginal){
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
}
If above is your full code then, basic problem is there, you haven't define btn. You need to define it before using it, else when you ar egoing to click on the button it will not work. and this might closing your application.
btn=(Button) findViewById(R.id.button1);
Related
I want to create a bitmap from an imageView, but I first need to rotate my imageView before converting the bitmap. I use the following code to convert the imageView to Bitmap.
BitmapDrawable drawable = (BitmapDrawable) imgPhoto.getDrawable();
Bitmap photo = drawable.getBitmap();
The imageView implements a rotation gesture. I want to be able to rotate the imageView and then create a Bitmap using the rotated imageView. However, it seems my Bitmap is still getting the original imageView instead of the rotated position. The following is the complete code. Thank you.
public class MainActivity extends AppCompatActivity implements RotationGestureDetector.OnRotationGestureListener{
private ImageView imgPhoto, imgBackground, imgCombine;
private RotationGestureDetector mRotationDetector;
private Button btnCombine;
private float angle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRotationDetector = new RotationGestureDetector(this);
imgPhoto = (ImageView) findViewById(R.id.imgPhoto);
imgBackground = (ImageView) findViewById(R.id.imgBackground);
collageImage = (ImageView) findViewById(R.id.imgCombine);
btnCombine = (Button)findViewById(R.id.btnCombineImage);
btnCombine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable drawable = (BitmapDrawable) imgPhoto.getDrawable();
Bitmap photo = drawable.getBitmap();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event){
mRotationDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
#Override
public void OnRotation(RotationGestureDetector rotationDetector) {
angle = rotationDetector.getAngle();
Log.d("RotationGestureDetector", "Rotation: " + Float.toString(angle));
imgPhoto.setRotation(imgPhoto.getRotation() + (-angle));
}
}
To rotate ImageView:
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);
Source: https://stackoverflow.com/a/10104318/7639113
Then you can create the bitmap by using DrawingCache,
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
Try using this code after the onClick. It should provide a rotated bitmap with the angle specified.
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap rotatedPhoto = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true);
The rotate effect is actually applied at the Canvas level. So, what you can do is get the current Canvas augmentations and then draw your Bitmap into a new one with the changes.
Matrix transformMatrix = imgPhoto.getImageMatrix()
Bitmap original = photo;
Bitmap adjusted = Bitmap.createBitmap(original.getWidth(),
original.getHeight(),
original.getConfig());
Canvas canvas = new Canvas(adjusted);
canvas.setMatrix(transformMatrix);
canvas.drawBitmap(original, 0, 0, null);
//at this point adjusted bitmap contains the rotated image
I have this code to detect face from an image and draw a red rectangle around it, but I have a run time exception can anyone fix it please i have no idea what to do , i tried a lot of face detection code but also didn't work
{
public class MainActivity extends AppCompatActivity
{
Button btn = (Button) findViewById(R.id.button);
ImageView myImageView = (ImageView) findViewById(R.id.imgview);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable=true;
Bitmap myBitmap = BitmapFactory.decodeResource(
getApplicationContext().getResources(),
R.drawable.test1,
options);
Paint myRectPaint = new Paint();
myRectPaint.setStrokeWidth(5);
myRectPaint.setColor(Color.RED);
myRectPaint.setStyle(Paint.Style.STROKE);
Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
tempCanvas.drawBitmap(myBitmap, 0, 0, null);
FaceDetector faceDetector = new
FaceDetector.Builder(getApplicationContext()).setTrackingEnabled(false)
.build();
if(!faceDetector.isOperational()){
new AlertDialog.Builder(v.getContext()).setMessage("Could not set up the face detector!").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(myBitmap).build();
SparseArray<Face> faces = faceDetector.detect(frame);
for(int i=0; i<faces.size(); i++) {
Face thisFace = faces.valueAt(i);
float x1 = thisFace.getPosition().x;
float y1 = thisFace.getPosition().y;
float x2 = x1 + thisFace.getWidth();
float y2 = y1 + thisFace.getHeight();
tempCanvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, myRectPaint);
}
myImageView.setImageDrawable(new BitmapDrawable(getResources(),tempBitmap));
}
});
}
}
here is the exception
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hadeel.hadd/com.example.hadeel.hadd.MainActivity}: java.lang.NullPointerException
Button btn = (Button) findViewById(R.id.button);
ImageView myImageView = (ImageView) findViewById(R.id.imgview);
You shouldn't do initialization of variables which hold references to android widgets like above, because layout of activity is not inflated (method onCreate will run after creation of this object). You should move invocation of findViewById right after method setContentView
I wanted to know if it was possible to crop a picture to any other shape not just square, rectangle or circle.
Basically what I am looking for is that, the user can select a template of a png file (already present) and it cuts the picture in that shape.
Check out this code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageViewPreview = (ImageView) findViewById(R.id.imageview_preview);
new Thread(new Runnable() {
#Override
public void run() {
final Bitmap source = BitmapFactory.decodeResource(MainActivity.this.getResources(),
R.drawable.source);
final Bitmap mask = BitmapFactory.decodeResource(MainActivity.this.getResources(),
R.drawable.mask);
final Bitmap croppedBitmap = cropBitmap(source, mask);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageViewPreview.setImageBitmap(croppedBitmap);
}
});
}
}).start();
}
private Bitmap cropBitmap(final Bitmap source, final Bitmap mask){
final Bitmap croppedBitmap = Bitmap.createBitmap(
source.getWidth(), source.getHeight(),
Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(croppedBitmap);
canvas.drawBitmap(source, 0, 0, null);
final Paint maskPaint = new Paint();
maskPaint.setXfermode(
new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
canvas.drawBitmap(mask, 0, 0, maskPaint);
return croppedBitmap;
}
}
The main function is the "cropBitmap" function. Basically it receives two bitmaps, a source and a mask, and then it "crops" the source bitmap using the mask's shape.
This is my source bitmap:
This is the mask bitmap:
And this is the result:
Also, check out this great presentation, this might help you too: Fun with Android shaders and filters
I have loaded a floor plan image and converted it into a Bitmap. And I have a circle drawn onto that floor plan image. This circle shows the current position of this user on the floor plan.
The problem is, when it comes a slow response from the server, multiple circle are drawn on the floor plan
Here is my code :
public void onServiceUpdate(ServiceState state) {
final int i, j;
i = state.getImagePoint().getI();
j = state.getImagePoint().getJ();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
final ImageView imageFloor = (ImageView) findViewById(R.id.imageView);
final Bitmap bitmapCircle = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
Canvas canvas = new Canvas(bitmapCircle);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
canvas.drawBitmap(bitmap, new Matrix(), null);
canvas.drawCircle(i, j, 10, paint);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageFloor.setImageBitmap(bitmapCircle);
}
});
and this is method calling floor plan image from indooratlas server.
public void loadFloorPlanImage(FloorPlan floorPlan) {
BitmapFactory.Options options = createBitmapOptions(floorPlan);
FutureResult<Bitmap> result = mIndoorAtlas.fetchFloorPlanImage(floorPlan,options);
result.setCallback(new ResultCallback<Bitmap>() {
#Override
public void onResult(final Bitmap result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(result);
log("onResult LoadFloorPlanImage");
}
});
}
is there any ideas or some advice how to clear the circle inside floor plan bitmap ?
You could do like this:
onServiceUpdate(...){
final ImageView imageFloor = (ImageView) findViewById(R.id.imageView);
imageFloor.setVisibility(View.GONE);
....
runOnUiThread(new Runnable() {
#Override
public void run() {
imageFloor.setVisibility(View.VISIBLE);
imageFloor.setImageBitmap(bitmapCircle);
But your question isn't very clear, I would not be surprised if I didn't understand what you meant
I need to be able to create a custom image through code, and then set that image to an imageview
I want this image to have a solid background colour, a title and an icon.
I want it to be customisable so that I can call to create an image with values
for example
createImage(String bckgColourHex, String title, int iconResource){
// create image using value here
return image.
}
Then I can use the drawable to set it to my imageView
This is what I am trying so far
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image = (ImageView) findViewById(R.id.imageView1);
BitmapDrawable customImage = writeOnDrawable(R.drawable.background_gradient, "TEXT GOES HERE");
image.setBackgroundDrawable(customImage);
}
public BitmapDrawable writeOnDrawable(int drawableId, String text){
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
Canvas canvas = new Canvas(bm);
canvas.drawText(text, 0, bm.getHeight()/2, paint);
return new BitmapDrawable(bm);
}
Thank you
public static Drawable makeBorderedDrawable(Context mContext, int width, String xCode, Boolean unAvail) {
Paint p = new Paint();
Bitmap bkg = null;
final int FULL_ALPHA = 0xFF123456; // of whatever color you want
int pixel = FULL_ALPHA;
// first create a mutable bitmap
bkg = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bkg);
p.setColor(pixel);
c.drawCircle(width / 2, width / 2, width / 2, p);
// or draw rect, or lines, or drawtext....or whatever
return new BitmapDrawable(mContext.getResources(), bkg);
// or you could return a Bitmap if you prefer.
}