I'm doing an android project in which I need to let the user to take a picture and out it as a profile picture
I'm not sure what's wrong but the image is not shown after it's taken.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTIVITY_START_CAMERA_APP && resultCode == RESULT_OK)
{
Bitmap imageBitmap = (Bitmap) data.getExtras().get("date");
profilePicture.setImageBitmap(imageBitmap);
wasPhoto = true;
Toast.makeText(this, "Profile Picture taken successfully",
Toast.LENGTH_SHORT).show();
}
}
<ImageView
android:id="#+id/IVAddPicture"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="#drawable/person_image" />
Before
After
Try below code in your onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTIVITY_START_CAMERA_APP && resultCode == RESULT_OK
&& null != data) {
try {
Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(mActivity.getContentResolver(), selectedImage);
profilePicture.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I'm trying to get multiple images from the gallery, show it in >Recyclerview, and sending it to server but showing this error >Here's my code to write the images to file,the error is at the >initialization of inputstream
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Data any THING", String.valueOf(data));
if (requestCode == ImagePicker.IMAGE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
List<String> mPaths = data.getStringArrayListExtra(ImagePicker.EXTRA_IMAGE_PATH);
Log.d("mPaths MainActivity", String.valueOf(mPaths));
for (int i = 0; i < mPaths.size(); i++) {
files.add(new File(mPaths.get(i)));
}
if (inputStream==null) {
for (int i = 0; i < files.size(); i++) {
try {
inputStream = getContentResolver().openInputStream(Uri.fromFile( files.get(i)));
Toast.makeText(this, "Inputstream"+String.valueOf(inputStream), Toast.LENGTH_SHORT).show();
bitmaps = BitmapFactory.decodeStream(inputStream);
Log.e("File", String.valueOf(files));
Log.e("stream", String.valueOf(inputStream));
editText.setText(String.valueOf(files)+String.valueOf(inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Log.d("DATASSSSSSSSSSSTTTT", String.valueOf(data.getData()));
Log.e("IMages From Stream", String.valueOf(bitmaps));
Log.d("Images from Steam", String.valueOf(bitmaps));
recyclerAdapter.fileMOthod(files);
if (bitmaps != null) {
resizeIMagestoAdapter();
imageResize(bitmaps);
} else {
}
}
}
}
}
The files array has only indices 0 to files.size()-1, but your i variable goes from 0 to files.size() in the loop:
for (int i = 0; i < files.size()+1; i++)
Therefore, files.get(i) fails with the IndexOutOfBoundsException.
Index: 2, Size: 2 means that the size of files is 2 (it has only indices 0 and 1), but you are trying to access index 2.
I am trying to pass this method through my main() function but The loadMap already has the bufferreader so I am trying to use that rather than creating my own new buffer reader. How can I do this?
public static void main(String args[]) {
//throw exceptions here if args is empty
filename = args[0];
System.out.println(MapIO.loadMap(filename)[0]);
System.out.println(MapIO.loadMap(filename)[1]);
if (args.length < 1) {
System.err.println("Usage:\n" +"java CrawlGui mapname");
System.exit(1);
}
List<String> names=new LinkedList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new
File(filename)))) {
String line;
while ((line = reader.readLine()) != null)
names.add(line);
System.out.println(names);
} catch (IOException e) {
e.printStackTrace();
}
MapIO.loadMap(filename);
launch(args);
}
/** Read information from a file created with saveMap
* #param filename Filename to read from
* #return null if unsucessful. If successful, an array of two Objects.
[0] being the Player object (if found) and
[1] being the start room.
* #detail. Do not add the player to the room they appear in, the caller
will be responsible for placing the player in the start room.
*/
public static Object[] loadMap(String filename) {
Player player = null;
try {
BufferedReader bf = new BufferedReader(
new FileReader(filename));
String line = bf.readLine();
int idcap = Integer.parseInt(line);
Room[] rooms = new Room[idcap];
for (int i = 0; i < idcap; ++i) {
line = bf.readLine();
if (line == null) {
return null;
}
rooms[i] = new Room(line);
}
for (int i = 0; i < idcap; ++i) { // for each room set up exits
line = bf.readLine();
int exitcount=Integer.parseInt(line);
for (int j=0; j < exitcount; ++j) {
line = bf.readLine();
if (line == null) {
return null;
}
int pos = line.indexOf(' ');
if (pos < 0) {
return null;
}
int target = Integer.parseInt(line.substring(0,pos));
String exname = line.substring(pos+1);
try {
rooms[i].addExit(exname, rooms[target]);
} catch (ExitExistsException e) {
return null;
} catch (NullRoomException e) {
return null;
}
}
}
for (int i = 0;i<idcap;++i) {
line = bf.readLine();
int itemcount = Integer.parseInt(line);
for (int j = 0; j < itemcount; ++j) {
line = bf.readLine();
if (line == null) {
return null;
}
Thing t = decodeThing(line, rooms[0]);
if (t == null) {
return null;
}
if (t instanceof Player) { // we don't add
player = (Player)t; // players to rooms
} else {
rooms[i].enter(t);
}
}
}
Object[] res = new Object[2];
res[0] = player;
res[1] = rooms[0];
return res;
} catch (IOException ex) {
return null;
} catch (IndexOutOfBoundsException ex) {
return null;
} catch (NumberFormatException nfe) {
return null;
}
}
You shouldn't do anything in main() other than call launch(). Move all the other startup code to your start() method. You can get the content of the args array using getParameters().getRaw():
#Override
public void start(Stage primaryStage) {
//throw exceptions here if args is empty
filename = getParameters().getRaw().get(0);
System.out.println(MapIO.loadMap(filename)[0]);
System.out.println(MapIO.loadMap(filename)[1]);
if (args.length < 1) {
System.err.println("Usage:\n" +"java CrawlGui mapname");
System.exit(1);
}
List<String> names=new LinkedList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new
File(filename)))) {
String line;
while ((line = reader.readLine()) != null)
names.add(line);
System.out.println(names);
} catch (IOException e) {
e.printStackTrace();
}
Object[] whateverThisThingIs = MapIO.loadMap(filename);
// Now you have access to everything you need, at the point where you need it.
// existing start() code goes here...
}
public static void main(String args[]) {
launch(args);
}
I have set list border using trigger according to my requirement but when I scroll up the listview and selected view cell is gone than I scroll down when ViewCell is appearing on screen than selected border is gone
To prevent this I also created frame renderer but still ViewCell border gone.
Attached image here
class FrameHighLightRenderer : VisualElementRenderer<Frame>
{
ACanvas _canvas = null;
private FrameDrawable _frameDrawable;
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
if (_frameDrawable != null && e.NewElement.ClassId != null) //This block execute while any cell appearing in scroll time up/dowm
{ // I added classId =10 to identify colored/selected cell
if (e.NewElement.ClassId=="10")
{
e.NewElement.OutlineColor = Xamarin.Forms.Color.Red;
this.Invalidate();
}
else
{
e.NewElement.BackgroundColor = Xamarin.Forms.Color.TransParent;
}
}
else
{
UpdateBackground();
}
}
}
void UpdateBackground()
{
_frameDrawable = new FrameDrawable(Element, Context.ToPixels);
this.SetBackground(_frameDrawable);
}
class FrameDrawable : Drawable
{
readonly Frame _frame;
readonly Func<double, float> _convertToPixels;
public ACanvas _canvas;
bool _isDisposed;
Bitmap _normalBitmap;
public FrameDrawable(Frame frame, Func<double, float> convertToPixels)
{
_frame = frame;
_convertToPixels = convertToPixels;
frame.PropertyChanged += FrameOnPropertyChanged;
}
public override bool IsStateful
{
get { return false; }
}
public override int Opacity
{
get { return 0; }
}
public override void Draw(ACanvas canvas)
{
SetBorderColorandWidth(canvas);
}
private void SetBorderColorandWidth(ACanvas canvas)
{
int width = Bounds.Width();
int height = Bounds.Height();
if (width <= 0 || height <= 0)
{
if (_normalBitmap != null)
{
_normalBitmap.Dispose();
_normalBitmap = null;
}
return;
}
if (_normalBitmap == null || _normalBitmap.Height != height || _normalBitmap.Width != width)
{
_normalBitmap = CreateBitmap(false, width, height);
}
Bitmap bitmap = _normalBitmap;
// if(canvas)
if (InspectionQAPage._highlight_color)
{
using (var paint = new Paint { AntiAlias = true })
using (var path = new Path())
using (Path.Direction direction = Path.Direction.Cw)
using (Paint.Style style = Paint.Style.Stroke)
using (var rect = new RectF(0, 0, width, height))
{
float rx = Forms.Context.ToPixels(4);
float ry = Forms.Context.ToPixels(4);
path.AddRoundRect(rect, rx, ry, direction);
if (this._frame.OutlineColor == Xamarin.Forms.Color.Red)
{
paint.Color = Android.Graphics.Color.Red;
this._frame.ClassId = "10";
// this._frame.BackgroundColor = Xamarin.Forms.Color.Red;
// paint.SetStyle = (Paint.Style)(Resource.Style.WithBorder);
}
else
{
// paint.Reset();
paint.Color = Android.Graphics.Color.Transparent;
// this._frame.BackgroundColor = Xamarin.Forms.Color.Transparent;
}
paint.StrokeWidth = 10f; //set outline stroke
paint.SetStyle(style);
canvas.DrawPath(path, paint);
}
InspectionQAPage._highlight_color = false;
}
else
{
using (var paint = new Paint())
canvas.DrawBitmap(bitmap, 0, 0, paint);
}
// InvalidateSelf();
}
public override void SetAlpha(int alpha)
{
}
public override void SetColorFilter(ColorFilter cf)
{
}
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
if (_normalBitmap != null)
{
_normalBitmap.Dispose();
_normalBitmap = null;
}
_isDisposed = true;
}
base.Dispose(disposing);
}
protected override bool OnStateChange(int[] state)
{
return false;
}
Bitmap CreateBitmap(bool pressed, int width, int height)
{
Bitmap bitmap;
using (Bitmap.Config config = Bitmap.Config.Argb8888)
if (width <= 0 || height <= 0)
{
return null;
}
else
bitmap = Bitmap.CreateBitmap(width, height, config);
using (var canvas = new ACanvas(bitmap))
{
// DrawCanvas(canvas, width, height, pressed);
}
return bitmap;
}
void FrameOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName ||
e.PropertyName == Frame.OutlineColorProperty.PropertyName ||
e.PropertyName == Frame.CornerRadiusProperty.PropertyName)
{
try
{
if (_normalBitmap == null)
return;
int width = Bounds.Width();
int height = Bounds.Height();
if (width <= 0 || height <= 0)
{
return;
}
if (_canvas == null)
{
var canvas = new ACanvas(_normalBitmap);
_canvas = canvas;
_canvas.DrawColor(global::Android.Graphics.Color.Red, PorterDuff.Mode.Clear);
DrawCanvas(_canvas, width, height, false, sender);
}
else
{
_canvas.DrawColor(global::Android.Graphics.Color.Red, PorterDuff.Mode.Clear);
DrawCanvas(_canvas, width, height, false, sender);
}
InvalidateSelf();
}
catch (Exception ex)
{
Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>" + ex);
throw;
}
}
}
public void DrawCanvas(ACanvas canvas, int width, int height, bool pressed, object sender)
{
using (var paint = new Paint { AntiAlias = true })
using (var path = new Path())
using (Path.Direction direction = Path.Direction.Cw)
using (Paint.Style style = Paint.Style.Stroke)
using (var rect = new RectF(0, 0, width, height))
{
float rx = Forms.Context.ToPixels(4);
float ry = Forms.Context.ToPixels(4);
path.AddRoundRect(rect, rx, ry, direction);
if (((Frame)sender).OutlineColor == Xamarin.Forms.Color.Red)
{
paint.Color = Android.Graphics.Color.Red;
((Frame)sender).ClassId = "10";
}
else
{
((Frame)sender).BackgroundColor = Xamarin.Forms.Color.Transparent;
}
paint.StrokeWidth = 10f; //set outline stroke
paint.SetStyle(style);
canvas.DrawPath(path, paint);
}
}
}
}
}
I'm a new developer.I'm trying to make a simple program in which we can draw multiple shapes like Rectangle, Ellipse, Line, etc. The problem which I'm facing right now is that when I click the mouse and drag to draw on mouseDown and mouseMove event I'm not able to see the shape. The shape appears on the pictureBox only when I leave the mouse.
I want the shape to appear and move with the mouse as the user draws it just like in paint application by Microsoft.
I tried using Refresh() function while drawing but it removes the old shapes which was already drawn in the pictureBox.
Below is the code I'm using. need some suggestions.
bool draw = false;
bool isMouseDown = false;
int x, y, lx, ly = 0;
Item currItem;
Pen pen = new Pen(Color.Red,1);
public enum Item
{
Rectangle, Ellipse, Line, Pencil, Eraser
}
private void btnROIDraw_Click(object sender, EventArgs e)
{
if (menuStripRoi.Visible == false)
{
menuStripRoi.Visible = true;
}
else
{
menuStripRoi.Visible = false;
draw = false;
}
}
private void pictureBoxROI_MouseDown(object sender, MouseEventArgs e)
{
x = e.X;
y = e.Y;
isMouseDown = true;
//draw = true;
}
private void pictureBoxROI_MouseUp(object sender, MouseEventArgs e)
{
lx = e.X;
ly = e.Y;
if (draw)
{
Graphics g = pictureBoxROI.CreateGraphics();
switch (currItem)
{
case Item.Rectangle:
g.DrawRectangle(pen, x, y, e.X - x, e.Y - y);
break;
case Item.Ellipse:
g.DrawEllipse(pen, x, y, e.X - x, e.Y - y);
break;
case Item.Line:
g.DrawLine(pen, x, y, e.X, e.Y);
break;
}
g.Dispose();
}
isMouseDown = false;
}
private void pictureBoxROI_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
if (draw)
{
Graphics g = pictureBoxROI.CreateGraphics();
switch (currItem)
{
case Item.Pencil:
g.FillEllipse(new SolidBrush(Color.Red), e.X - x + x, e.Y - y + y, 2, 2);
break;
case Item.Eraser:
g.FillEllipse(new SolidBrush(pictureBoxROI.BackColor), e.X - x + x, e.Y - y + y, 20, 20);
break;
}
g.Dispose();
}
}
}
private void pictureBoxROI_Paint(object sender, PaintEventArgs e)
{
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
pictureBoxROI.Refresh();
}
private void rectangleToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Rectangle;
draw = true;
}
private void ellipseToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Ellipse;
draw = true;
}
private void lineToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Line;
draw = true;
}
private void pencilToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Pencil;
draw = true;
}
private void eracerToolStripMenuItem_Click(object sender, EventArgs e)
{
currItem = Item.Eraser;
draw = true;
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
pictureBoxROI.Refresh();
pictureBoxROI.Image = null;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog o = new OpenFileDialog();
o.Filter = "Png files|*.png|jpeg files|*jpg|bitmaps|*.bmp";
if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pictureBoxROI.Image = (Image)Image.FromFile(o.FileName).Clone();
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(pictureBoxROI.Width, pictureBoxROI.Height);
Graphics g = Graphics.FromImage(bmp);
Rectangle rect = pictureBoxROI.RectangleToScreen(pictureBoxROI.ClientRectangle);
g.CopyFromScreen(rect.Location, Point.Empty, pictureBoxROI.Size);
g.Dispose();
SaveFileDialog s = new SaveFileDialog();
s.Filter = "Png files|*.png|jpeg files|*jpg|bitmaps|*.bmp";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (File.Exists(s.FileName))
{
File.Delete(s.FileName);
}
if (s.FileName.Contains(".jpg"))
{
bmp.Save(s.FileName, ImageFormat.Jpeg);
}
else if (s.FileName.Contains(".png"))
{
bmp.Save(s.FileName, ImageFormat.Png);
}
else if (s.FileName.Contains(".bmp"))
{
bmp.Save(s.FileName, ImageFormat.Bmp);
}
}
}
Found a solution to my question.
This article explains in detail everything about drawing with GDI+. Worth having a look
http://www.codeproject.com/Articles/17893/Extensions-to-DrawTools
This program should work like join the dots , the user selects the number of dots to display and is able to draw on the canvas, the problem is with the save , whenever i try to save it isnt working at all , it gives me a black rectangle..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Painting2
{
public partial class Form1 : Form
{
Bitmap drawing;
bool draw = false;
Color C = Color.Black;
int size = 14;
bool startdraw = false;
public Form1(string parameter1)
{
InitializeComponent();
this.Text = parameter1;
}
private void Form1_Load(object sender, EventArgs e)
{
drawing = new Bitmap (pnlcanvas.Width, pnlcanvas.Height, pnlcanvas.CreateGraphics());
cbdots.Items.Add("2");
cbdots.Items.Add("3");
cbdots.Items.Add("4");
cbdots.Items.Add("5");
cbdots.Items.Add("6");
cbdots.Items.Add("7");
cbdots.Items.Add("8");
cbdots.Items.Add("9");
cbdots.Items.Add("10");
cbdots.Items.Add("11");
cbdots.Items.Add("12");
cbdots.Items.Add("13");
cbdots.Items.Add("14");
cbdots.Items.Add("15");
}
private void pnlcanvas_MouseDown(object sender, MouseEventArgs e)
{
draw = true;
Graphics g = Graphics.FromImage(drawing);
SolidBrush b = new SolidBrush(C);
if (startdraw == true)
{
g.FillEllipse(b, e.X, e.Y, size, size);
pnlcanvas.CreateGraphics().DrawImageUnscaled(drawing, new Point(0, 0));
}
}
private void pnlcanvas_MouseUp(object sender, MouseEventArgs e)
{
draw = false;
}
private void pnlcanvas_Move(object sender, EventArgs e)
{
}
private void pnlcanvas_MouseMove(object sender, MouseEventArgs e)
{
if (draw == true && startdraw == true)
{
Graphics g = Graphics.FromImage(drawing);
SolidBrush b = new SolidBrush(C);
g.FillEllipse(b, e.X, e.Y, size, size);
pnlcanvas.CreateGraphics().DrawImageUnscaled(drawing, new Point(0, 0));
}
}
private void btncolor_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
C = Color.White;
size = 25;
}
private void button2_Click(object sender, EventArgs e)
{
drawing = new Bitmap(pnlcanvas.Width, pnlcanvas.Height, pnlcanvas.CreateGraphics());
pnlcanvas.CreateGraphics().Clear(Color.White);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btnsave_Click(object sender, EventArgs e)
{
//if (saveDialog.ShowDialog() == DialogResult.OK)
//{
// Bitmap tosave = new Bitmap(pnlcanvas.Width, pnlcanvas.Height);
// pnlcanvas.DrawToBitmap(tosave, new Rectangle(0, 0, pnlcanvas.Width, pnlcanvas.Height));
// tosave.Save(saveDialog.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
//}
using (Bitmap bitmap = new Bitmap(pnlcanvas.ClientSize.Width,
pnlcanvas.ClientSize.Height))
{
pnlcanvas.DrawToBitmap(bitmap, pnlcanvas.ClientRectangle);
bitmap.Save(#"C:\Users\xejns_000\Desktop\TestDrawToBitmap.bmp", ImageFormat.Bmp);
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void btnstart_Click(object sender, EventArgs e)
{
DialogResult result = cd.ShowDialog();
if (result == DialogResult.OK)
{
C = cd.Color;
}
startdraw = true;
}
private void cbdots_SelectedIndexChanged(object sender, EventArgs e)
{
drawing = new Bitmap(pnlcanvas.Width, pnlcanvas.Height, pnlcanvas.CreateGraphics()); //clearing
pnlcanvas.CreateGraphics().Clear(Color.White); //clearing
Random r = new Random();
for (int i = 0; i <= Convert.ToInt32(cbdots.SelectedItem.ToString()) -1; i++)
{
Color RandC = Color.Black; ;
int randomcolor = r.Next(1, 11);
int randomx = r.Next(10, 730);
int randomy = r.Next(10, 390);
switch (randomcolor) // choosing random color
{
case 1:
RandC = Color.PaleVioletRed;
break;
case 2:
RandC = Color.PowderBlue;
break;
case 3:
RandC = Color.Fuchsia;
break;
case 4:
RandC = Color.DarkGoldenrod;
break;
case 5:
RandC = Color.LavenderBlush;
break;
case 6:
RandC = Color.Tomato;
break;
case 7:
RandC = Color.SpringGreen;
break;
case 8:
RandC = Color.Wheat;
break;
case 9:
RandC = Color.Salmon;
break;
case 10:
RandC = Color.LightSteelBlue;
break;
}
Graphics g = Graphics.FromImage(drawing); // painting dots
SolidBrush b = new SolidBrush(RandC); // painting dots
g.FillEllipse(b, randomx, randomy, 40, 40); // painting dots
pnlcanvas.CreateGraphics().DrawImageUnscaled(drawing, new Point(0, 0));
}
}
}
}