I'm currently developing an app and from within the app I'd like to let the user select custom images to use.
Right now I use
Code:
public final int GOT_IMAGE =1;
private void getImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
mUri = Uri.fromFile(new
File(Environment.getExternalStorageDirectory(),"temp_image" +
".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent,GOT_IMAGE );
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode != RESULT_OK) {
customImgChk.setChecked(false);
return;
}
if (requestCode == GOT_IMAGE) {
Bitmap image = BitmapFactory.decodeFile(mUri.getPath());
if (image!=null)
{
image = WPUtil.resizeBitmap(image, WPUtil.IMAGE_SIZE_X,
WPUtil.IMAGE_SIZE_Y);
}
else
{
customImgChk.setChecked(false);
Toast.makeText(this.getApplicationContext(), "Failed to grab
image!", Toast.LENGTH_LONG).show();
}
}
}
This works great on a few devices but not all. I'd really like to come up with a universal way to perform this function but I have not found a way to do it yet.
I've thought about writing up my own image selector and cropper but I'd rather not re-invent the wheel.
Can anybody suggest a decent app/library that I can use to select and or crop photos from within my app?
ImageJ is great. It is a stand alone app but there are published apis for integrating into your own apps.
*its better than that, its open source and you can use the jar and just ignore the gui library
Might look into that
http://rsbweb.nih.gov/ij/
From something awesome
Related
Hi all,
I'm trying to have transparent PNGs on my screen.
What is the best way to doing this ? I'm in C#, I tried DirectX, but it doesn't work.
What am I doing wrong ?
My code :
Code:
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.WindowsMobile.DirectX;
using Microsoft.WindowsMobile.DirectX.Direct3D;
using System.Runtime.InteropServices;
namespace Microsoft.Samples.MD3DM
{
// The main class for this sample
public class SimpleSMS : Form
{
// Our global variables for this project
Device device = null;
Texture texture = null;
Sprite sprite = null;
Rectangle rect;
public SimpleSMS()
{
// Set the caption
this.Text = "SimpleSMS";
this.MinimizeBox = false;
}
// Prepare the rendering device
public bool InitializeGraphics()
{
try
{
// Now let's setup our D3D parameters
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Default, this, CreateFlags.None, presentParams);
this.OnCreateDevice(device, null);
}
catch (DirectXException)
{
return false;
}
return true;
}
void OnCreateDevice(object sender, EventArgs e)
{
texture = TextureLoader.FromFile(device, @"badge.png");
sprite = new Sprite(device);
rect = new Rectangle(0, 0, 48, 48);
}
// All rendering for each frame occurs here
private void Render()
{
if (device != null)
{
device.Clear(ClearFlags.Target, System.Drawing.Color.Black, 1.0f, 0);
//Begin the scene
device.BeginScene();
device.RenderState.SourceBlend = Blend.SourceAlpha;
device.RenderState.DestinationBlend = Blend.InvSourceAlpha;
device.RenderState.AlphaBlendEnable = true;
sprite.Begin(SpriteFlags.AlphaBlend);
sprite.Draw(texture, rect, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(100.0f, 100.0f, 0.0f), Color.White.ToArgb());
sprite.End();
//End the scene
device.EndScene();
device.Present();
}
}
// Called to repaint the window
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
// Render on painting
this.Render();
// Render again
this.Invalidate();
}
// Called to repaint the window background
protected override void OnPaintBackground(
System.Windows.Forms.PaintEventArgs e)
{
// Do nothing to ensure that the rendering area is not overdrawn
}
// Close the window when Esc is pressed
protected override void OnKeyPress(
System.Windows.Forms.KeyPressEventArgs e)
{
// Esc was pressed
if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.Escape)
this.Close();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
SimpleSMS frm = new SimpleSMS();
// Initialize Direct3D
if (!frm.InitializeGraphics())
{
MessageBox.Show("Could not initialize Direct3D. " +
"This tutorial will exit.");
return;
}
Application.Run(frm);
}
}
}
Thanks for answers,
Scuse my bad english :-/
Not sure this helps, but RLTODAY works very well with transparent pngs in any WM version, and recently he released the source code:
http://rotlaus-software.de/forum/index.php?topic=1847.0
You can use ImagingFactory in OpenNETCF or other wrapper over the internet. PNGs with alpha work work for me.
AlphaControls
There is a project on Codeplex that can help you with transparency called AlphaControls. Also have a look on codeproject at the iPhone app clone
moneytoo said:
You can use ImagingFactory in OpenNETCF or other wrapper over the internet. PNGs with alpha work work for me.
Click to expand...
Click to collapse
Thank you all for answers ...
I tried OpenNetCF, without any result.
Do you have a piece of code in example ?
Try this:
http://www.codeplex.com/alphamobilecontrols
Or this:
http://johan.andersson.net/blog/2007/10/solution-for-transparent-images-on.html
Hi,
im playing around with the Camera Service. The preview mode works well, but if I take a picture and save it, it is a lot darker as in the preview. I tried it with the delivered camera app and there is no such problem.
I tried it with many diffrent values (iso, brightness, scenemode, whitebalance), but nothing changed, but the preview. It seems, that the preferences only have effect in the previewmode.
Device: altek A14 leo
OS: Android 2.1
Picture saved by the standard camera app:
abload.de/img/stdapp8uql.jpg
Preview mode:
abload.de/img/previewrne6.jpg
Picture saved by my app:
abload.de/img/myappiugc.jpg
parameters of the camera
Code:
atk-frame=0
brightness-max=12
brightness-min=0
brightness=6
camera-id=1
contrast-max=2
contrast-min=0
contrast=1
effect-values=none,mono,sepia,whiteboard
effect=none
flash-mode-values=off,auto,on,red-eye
flash-mode=off
focus-mode-values=auto,infinity
focus-mode=auto
gps-altitude=0
gps-latitude=0.0
gps-longitude=0.0
gps-timestamp=1199145600
iso-values=auto,80,100,200,400,800,1600,3200
iso=auto
jpeg-quality=100
jpeg-thumbnail-height=384
jpeg-thumbnail-quality=100
jpeg-thumbnail-width=512
max-zoom=9
metering-values=spot,center,matrix
metering=center
min-zoom=0
orientation=landscape
picture-format-values=jpeg
picture-format=jpeg
picture-size-values=2048x1536,1280x960
picture-size=2048x1536
preview-format-values=yuv420sp
preview-format=yuv420sp
preview-frame-rate-values=15
preview-frame-rate=15
preview-size-values=640x480
preview-size=640x480
rotation=0
saturation-max=0
saturation-min=2
saturation=1
scene-mode-values=auto,portrait,landscape,night,beach,snow,sunset,fireworks,sports,candlelight
scene-mode=auto
SD9-poweron-mode=0
sharpness-max=2
sharpness-min=0
sharpness=1
smooth-zoom-supported=true
whitebalance-values=auto,fluorescent,daylight,cloudy-daylight
whitebalance=auto
zoom-factors=100,130,160,190,220,250,280,310,340,360,400
zoom-supported=true
zoom=0
Code:
private OnClickListener cameraClickListener = new OnClickListener() {
public void onClick(View v) {
inPreview = false;
cam.takePicture(null, null, photoCallback);
}
};
PictureCallback photoCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePhotoTask().execute(data);
startPreview();
}
};
class SavePhotoTask extends AsyncTask<byte[], String, String> {
protected String doInBackground(byte[]... imageData) {
File photo = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(imageData[0]);
fos.close();
Log.i("IMAGE SAVED ASYNC", photo.getPath());
} catch (java.io.IOException e) {
Log.e("Error", "Exception in photoCallback", e);
}
return (null);
}
}
Does anybody have an idea, what causes this behaviour?
thanks.
rgds
I am not sure what happening with you. But as far as your codes it should work well. try other camera apps. Like 360. But problem persist then go to service center. The problem is with hardware.
Hi,
sorry for the late response. It was no hardware issue. I just had to call autoFocus and takePicture in the AutoFocusCallback.
Code:
private OnClickListener cameraClickListener = new OnClickListener() {
public void onClick(View v) {
if (!isFocusing) {
isFocusing = true;
cam.autoFocus(autoFocusCallback);
}
}
};
AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
if (success) {
isFocusing = false;
camera.takePicture(null, null, photoCallback);
}
}
};
regards
I want to make a lockscreen application, so I made simple application.
But, this is too slow. Time from being on screen to seeing my application is almost 3 seconds.
Why this app is too slow?
Here is the my code.
(this method is included in the class that inherit BroadcastReceiver)
public void onReceive(Context context, Intent intent)
{
if (intent.getAction() == Intent.ACTION_SCREEN_OFF)
{
Toast.makeText(context, "Screen is off", Toast.LENGTH_SHORT).show();
Intent i = new Intent( context, MainActivity.class );
//i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_ONE_SHOT);
try
{
pi.send();
}
catch (CanceledException e)
{
e.printStackTrace();
}
}
}
I am writing an IRC Client, and so far as long as I dont send the app to the background and try to restore it it works fine. Tabs for multiple channels, the connected socket is in a bound service (started separately via INTENT and a startService call), etc and so on.
However, whenever I send the app to the background, then bring it back forward, the socket closes. I would have the same issue with screen rotation but I found the config setting that stops it from going through destroy/create on rotation. If I figure this out I may actually get rid of that since the issue will have been solved.
The other issue I seem to be having is that it takes a long time to re-bind to the service, and I have no idea why (the initial binding and startup is pretty quick, but re-binding to it seems to take forever, and when It does re-bind, the socket is closed).
Here are the code samples that I feel to be relevant, let me know if there's something more specific you want to see.
Code:
//This is the Service in question
public class ConnectionService extends Service{
private BlockingQueue<String> MessageQueue;
public final IBinder myBind = new ConnectionBinder();
public class ConnectionBinder extends Binder {
ConnectionService getService() {
return ConnectionService.this;
}
}
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private IRCServer server;
private WifiManager.WifiLock wLock;
private Thread readThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String line;
while ((line = reader.readLine( )) != null) {
//message parsing stuff
}
}
catch (Exception e) {}
}
});
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(MessageQueue == null)
MessageQueue = new LinkedBlockingQueue<String>();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return myBind;
}
@Override
public boolean stopService(Intent name) {
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.stopService(name);
}
@Override
public void onDestroy()
{//I put this here so I had a breakpoint in place to make sure this wasn't firing instead of stopService
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onDestroy();
}
public void SendMessage(String message)
{
try {
writer.write(message + "\r\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readLine()
{//this is called by the activity which consumes the service. Its just an accessor to MessageQueue
try {
if(!isConnected())
return null;
else
return MessageQueue.take();
} catch (InterruptedException e) {
return "";
}
}
public boolean ConnectToServer(IRCServer newServer)
{
try {
//create a new message queue (connecting to a new server)
MessageQueue = new LinkedBlockingQueue<String>();
//lock the wifi
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");
wLock.acquire();
server = newServer;
//connect to server
socket = new Socket();
socket.setKeepAlive(true);
socket.setSoTimeout(60000);
socket.connect(new InetSocketAddress(server.NAME, Integer.parseInt(server.PORT)), 10000);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//run basic login scripts.
String line;
while ((line = reader.readLine( )) != null) {
//server initialization stuff
}
//start the reader thread AFTER the primary login!!!
CheckStartReader();
if(server.START_CHANNEL == null || server.START_CHANNEL == "")
{
server.WriteCommand("/join " + server.START_CHANNEL);
}
//we're done here, go home everyone
} catch (NumberFormatException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
private void queueMessage(String line) {
try {
MessageQueue.put(line);
} catch (InterruptedException e) {
}
}
public boolean isConnected()
{
return socket.isConnected();
}
public void CheckStartReader()
{
if(this.isConnected() && !readThread.isAlive())
readThread.start();
}
}
Code:
//Here are the relevant portions of the hosting Activity that connects to the service
//NOTE: THE FOLLOWING CODE IS PART OF THE ACTIVITY, NOT THE SERVICE
private ConnectionService conn;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
conn = ((ConnectionService.ConnectionBinder)service).getService();
//debug toast
Toast.makeText(main_tab_page.this, "Connected", Toast.LENGTH_SHORT)
.show();
synchronized (_serviceConnWait) {
_serviceConnWait.notify();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
conn = null;//does this even run? Breakpoint here
}
};
@Override
protected void onSaveInstanceState(Bundle state){
super.onSaveInstanceState(state);
state.putParcelable("Server", server);
state.putString("Window", CurrentTabWindow.GetName());
//have to unbind, othewise we get that leaked service exception
unbindService(mConnection);
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(this.isFinishing())
stopService(new Intent(this, ConnectionService.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab_page);
localTabHost = (TabHost)findViewById(R.id.tabHostMain);
localTabHost.setup();
localTabHost.setOnTabChangedListener(new tabChange());
_serviceConnWait = new Object();
if(savedInstanceState == null)
{//initial startup, coming from Intent to start
//get server definition
server = (IRCServer)this.getIntent().getParcelableExtra(IRC_WINDOW);
server.addObserver(this);
AddTabView(server);
//this should only run the first time, all other calls to OnCreate should have something in SavedInstanceState
startService(new Intent(this, ConnectionService.class));
}
else
{
server = (IRCServer)savedInstanceState.getParcelable("Server");
String windowName = savedInstanceState.getString("Window");
//Add Needed Tabs
//Server
if(!(windowName.equals(server.GetName())))
AddTabView(server);
//channels
for(IRCChannel c : server.GetAllChannels())
if(!(windowName.equals(c.GetName())))
AddTabView(c);
//reset each view's text (handled by tabChange)
if(windowName.equals(server.GetName()))
SetCurrentTab(server.NAME);
else
SetCurrentTab(windowName);
ResetMainView(CurrentTabWindow.GetWindowTextSpan());
//Rebind to service
BindToService(new Intent(this, ConnectionService.class));
}
}
@Override
protected void onStart()
{
super.onStart();
final Intent ServiceIntent = new Intent(this, ConnectionService.class);
//check start connection service
final Thread serverConnect = new Thread(new Runnable() {
@Override
public void run() {
if(!BindToService(ServiceIntent))
return;
server.conn = conn;
conn.ConnectToServer(server);
server.StartReader();
if(server.START_CHANNEL != null && !server.START_CHANNEL.equals(""))
{
IRCChannel chan = server.FindChannel(server.START_CHANNEL);
if(chan != null)
{
AddTabView(chan);
}
else
{
server.JoinChannel(server.START_CHANNEL);
chan = server.FindChannel(server.START_CHANNEL);
AddTabView(chan);
}
}
}
});
serverConnect.start();
}
private boolean BindToService(Intent ServiceIntent)
{
int tryCount = 0;
bindService(ServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
while(conn == null && tryCount < 10)
{
tryCount++;
try {
synchronized (_serviceConnWait) {
_serviceConnWait.wait(1500);
}
}
catch (InterruptedException e) {
//do nothing
}
}
return conn != null;
}
Logcat...well...there isn't really any exception thrown, the code runs just fine...except that it closes the socket. I suppose that counts as an exception. Whenever I run the socket write command It throws a "Socket Closed" exception at me. No other crash involved.
Hello all ,
i'm trying to make a timer that will kick the user out after let's say a few seconds , i used asynctask for it
it supposed to work on all activities including one that uses a camera on a diffrent thread ( using vuforia api and needs internet )
for some reason when i do it the camera doesn't work
(the same thing happens when there is no internet connection - might be related)
any ideas why ?
here's my asynctask
Code:
private class LoadSessionASYNC extends AsyncTask<String, Void, String> {
long time;
long interval;
public LoadSessionASYNC(long seshTime, long interval) {
time = seshTime;
interval=inter;
}
@Override
protected String doInBackground(String... urls) {
while (time >0)
{
publishProgress();
try {
Thread.sleep(interval);
} catch (InterruptedException e) {e.printStackTrace();}
time= time-interval;
}
return null;
}
@Override
protected void onPostExecute(String result) {
Intent startfresh = new Intent(getBaseContext(),WelcomActivity.class);
startActivity(startfresh);
}
@Override
protected void onProgressUpdate(Void... values) {
Toast.makeText(getApplicationContext(), "time to finish : "+time/1000+"seconds", Toast.LENGTH_SHORT).show();
super.onProgressUpdate(values);
}
}