Search Results

Search found 510 results on 21 pages for 'bmp'.

Page 7/21 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Is there a fast alternative to creating a Texture2D from a Bitmap object in XNA?

    - by Matthew Bowen
    I've looked around a lot and the only methods I've found for creating a Texture2D from a Bitmap are: using (MemoryStream s = new MemoryStream()) { bmp.Save(s, System.Drawing.Imaging.ImageFormat.Png); s.Seek(0, SeekOrigin.Begin); Texture2D tx = Texture2D.FromFile(device, s); } and Texture2D tx = new Texture2D(device, bmp.Width, bmp.Height, 0, TextureUsage.None, SurfaceFormat.Color); tx.SetData<byte>(rgbValues, 0, rgbValues.Length, SetDataOptions.NoOverwrite); Where rgbValues is a byte array containing the bitmap's pixel data in 32-bit ARGB format. My question is, are there any faster approaches that I can try? I am writing a map editor which has to read in custom-format images (map tiles) and convert them into Texture2D textures to display. The previous version of the editor, which was a C++ implementation, converted the images first into bitmaps and then into textures to be drawn using DirectX. I have attempted the same approach here, however both of the above approaches are significantly too slow. To load into memory all of the textures required for a map takes for the first approach ~250 seconds and for the second approach ~110 seconds on a reasonable spec computer. If there is a method to edit the data of a texture directly (such as with the Bitmap class's LockBits method) then I would be able to convert the custom-format images straight into a Texture2D and hopefully save processing time. Any help would be very much appreciated. Thanks

    Read the article

  • C# async callback on disposed form

    - by Rodney Burton
    Quick question: One of my forms in my winform app (c#) makes an async call to a WCF service to get some data. If the form happens to close before the callback happens, it crashes with an error about accessing a disposed object. What's the correct way to check/handle this situation? The error happens on the Invoke call to the method to update my form, but I can't drill down to the inner exception because it says the code has been optimized. The Code: public void RequestUserPhoto(int userID) { WCF.Service.BeginGetUserPhoto(userID, new AsyncCallback(GetUserPhotoCB), userID); } public void GetUserPhotoCB(IAsyncResult result) { var photo = WCF.Service.EndGetUserPhoto(result); int userID = (int)result.AsyncState; UpdateUserPhoto(userID, photo); } public delegate void UpdateUserPhotoDelegate(int userID, Binary photo); public void UpdateUserPhoto(int userID, Binary photo) { if (InvokeRequired) { var d = new UpdateUserPhotoDelegate(UpdateUserPhoto); Invoke(d, new object[] { userID, photo }); } else { if (photo != null) { var ms = new MemoryStream(photo.ToArray()); var bmp = new System.Drawing.Bitmap(ms); if (userID == theForm.AuthUserID) { pbMyPhoto.BackgroundImage = bmp; } else { pbPhoto.BackgroundImage = bmp; } } } }

    Read the article

  • How can i change background image of a button when hover or click in XAML for Windows 8?

    - by apero
    I got a question about changing the background image of a button when it's clicked. I tried searching on google but i couldn't find something that worked for me. Well here's my code <Button Grid.Column="0" Grid.Row="0" x:Name="btnHome" VerticalAlignment="Stretch" BorderBrush="{x:Null}" HorizontalAlignment="Stretch" Click="btnHome_Click" PointerEntered="btnHome_PointerEntered"> <Button.Template> <ControlTemplate TargetType="Button"> <Border x:Name="RootElement"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="MouseOver"> <Storyboard> //I want my background change here </Storyboard> </VisualState> <VisualState x:Name="Pressed"> <Storyboard> //And here </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border.Background> <ImageBrush ImageSource="images/back_button.png"/> </Border.Background> </Border> </ControlTemplate> </Button.Template> </Button> i also tried this private void btnHome_PointerEntered(object sender, PointerRoutedEventArgs e) { BitmapImage bmp = new BitmapImage(); Uri u = new Uri("ms-appx:images/back_button_mouseover.png", UriKind.RelativeOrAbsolute); bmp.UriSource = u; ImageBrush i = new ImageBrush(); i.ImageSource = bmp; btnHome.Background = i; } But unfortunately this worked neither

    Read the article

  • android - how to cache an image from a remote site

    - by Lynnooi
    Hi, Can anyone please provide me some example on how to save an image i fetch from websites into a cache. I had try to include the following function into my code and call it once i run the activity. public void getRemoteImage(String imageUrl) { imageUrl = "http://marga.mobile9.com/download/thumb/295/sexylady7_xo6npovn.jpg"; URL aURL = null; URLConnection conn = null; Bitmap bmp = null; CacheResult cache_result = CacheManager.getCacheFile(imageUrl, new HashMap()); if (cache_result == null) { try { aURL = new URL(imageUrl); conn = aURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); cache_result = new CacheManager.CacheResult(); CacheManager.saveCacheFile(imageUrl, cache_result); } catch (Exception e) { //return null; } } bmp = BitmapFactory.decodeStream(cache_result.getInputStream());*/ Toast.makeText(context,"Please work.. namo namo namo", Toast.LENGTH_SHORT).show(); //return bmp; } However, I got a nullPointerException. Can someone please help me with it as i'm quite new in android.

    Read the article

  • error: expected ',' or '...' before numeric constant

    - by goldfrapp04
    Just a Qt Gui Application with QDialog as the Base Class, the simplest type you can expect. I've programmed on Qt for several times but this is the first time I meet this problem... I've added minimal code to the program, and here's the code in dialog.h (which is mostly automatically generated) #ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <QPixmap> #include "bmp.h" namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private slots: void on_openButton_clicked(); private: Ui::Dialog *ui; BMP srcImage; QImage compressedImage[3]; }; #endif // DIALOG_H While I edit, the "public:" is underlined and says "unexpected token '('". When I try to build the program, it says in the line "Q_OBJECT", "error: expected ',' or '...' before numeric constant". I'm sure I've defined nothing related to it (to be exact, I defined an N and an n in file bmp.h, both are int). Any idea of what's wrong here? Thanks.

    Read the article

  • WP7 BarcodeManager - Invalid cross-thread access

    - by rpf
    I'm trying to use Windows Phone 7 Silverlight ZXing Barcode Scanning Library but I'm having some problems. I'm using a background worker to check the image, but when I do this: WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished); The code throws an exception: Invalid cross-thread access. Here is my code... void photoChooserTask_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { ShowImage(); System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage(); bmp.SetSource(e.ChosenPhoto); imgCapture.Source = bmp; this.Image = new BitmapImage(); this.Image.SetSource(e.ChosenPhoto); progressBar.Visibility = System.Windows.Visibility.Visible; txtStatus.Visibility = System.Windows.Visibility.Collapsed; worker.RunWorkerAsync(); } else ShowMain(); } void worker_DoWork(object sender, DoWorkEventArgs e) { try { Thread.Sleep(2000); WP7BarcodeManager.ScanMode = com.google.zxing.BarcodeFormat.UPC_EAN; WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished); } catch (Exception ex) { Debug.WriteLine("Error processing image.", ex); } } How can I solve this?

    Read the article

  • How to convert a byte array of 19200 bytes in size where each byte represents 4 pixels (2 bits per p

    - by Klinger
    I am communicating with an instrument (remote controlling it) and one of the things I need to do is to draw the instrument screen. In order to get the screen I issue a command and the instrument replies with an array of bytes that represents the screen. Below is what the instrument manual has to say about converting the response to the actual screen: The command retrieves the framebuffer data used for the display. It is 19200 bytes in size, 2-bits per pixel, 4 pixels per byte arranged as 320x240 characteres. The data is sent in RLE encoded form. To convert this data into a BMP for use in Windows, it needs to be turned into a 4BPP. Also note that BMP files are upside down relative to this data, i.e. the top display line is the last line in the BMP. I managed to unpack the data, but now I am stuck on how to actually go from the unpacked byte array to a bitmap. My background on this is pretty close to zero and my searches have not revealed much either. I am looking for directions and/or articles I could use to help me undestand how to get this done. Any code or even pseudo code would also help. :-) So, just to summarize it all: How to convert a byte array of 19200 bytes in size, where each byte represents 4 pixels (2 bits per pixel), to a bitmap arranged as 320x240 characters. Thanks in advance.

    Read the article

  • How do I tile and overlay images in WPF?

    - by imnlfn
    I'm very new to WPF and trying to port an application from VB6 to C# and XAML. What I need to do now is create one big image out of a number of small ones, arranged like a series of "tiles." Some of these smaller ones will have overlays superimposed on them. In VB6, accomplishing both the tiling and overlaying would simply be a matter of using the PaintPicture method with the PictureBox control. This is my attempt at the tiling and overlaying in one step (though really the overlaying could occur beforehand): ImageDrawing Drawing1 = new ImageDrawing(new BitmapImage(new Uri(@"c:\one.bmp", UriKind.Absolute)), new Rect(0, 0, 40, 130)); ImageDrawing Drawing2 = new ImageDrawing(new BitmapImage(new Uri(@"c:\two.bmp", UriKind.Absolute)), new Rect(40, 0, 45, 130)); ImageDrawing Drawing3 = new ImageDrawing(new BitmapImage(new Uri(@"c:\overlay.bmp", UriKind.Absolute)), new Rect(40, 0, 45, 130)); DrawingGroup myDrawingGroup = new DrawingGroup(); myDrawingGroup.Children.Add(Drawing1); myDrawingGroup.Children.Add(Drawing2); myDrawingGroup.Children.Add(Drawing3); myImage.Source = new DrawingImage(myDrawingGroup); The tiling works fine, but the overlay is a no-go. I was wondering if someone could point me towards a means of accomplishing the overlays and someone could indicate whether this is the best way to do the tiling. Thanks!!

    Read the article

  • Convertion of tiff image in Python script - OCR using tesseract

    - by PYTHON TEAM
    I want to convert a tiff image file to text document. My code perfectly as I expected to convert tiff images with usual font but its not working for french script font . My tiff image file contains text. The font of text is in french script format.I here is my code import Image import subprocess import util import errors tesseract_exe_name = 'tesseract' # Name of executable to be called at command line scratch_image_name = "temp.bmp" # This file must be .bmp or other Tesseract-compatible format scratch_text_name_root = "temp" # Leave out the .txt extension cleanup_scratch_flag = True # Temporary files cleaned up after OCR operation def call_tesseract(input_filename, output_filename): """Calls external tesseract.exe on input file (restrictions on types), outputting output_filename+'txt'""" args = [tesseract_exe_name, input_filename, output_filename] proc = subprocess.Popen(args) retcode = proc.wait() if retcode!=0: errors.check_for_errors() def image_to_string(im, cleanup = cleanup_scratch_flag): """Converts im to file, applies tesseract, and fetches resulting text. If cleanup=True, delete scratch files after operation.""" try: util.image_to_scratch(im, scratch_image_name) call_tesseract(scratch_image_name, scratch_text_name_root) text = util.retrieve_text(scratch_text_name_root) finally: if cleanup: util.perform_cleanup(scratch_image_name, scratch_text_name_root) return text def image_file_to_string(filename, cleanup = cleanup_scratch_flag, graceful_errors=True): If cleanup=True, delete scratch files after operation.""" try: try: call_tesseract(filename, scratch_text_name_root) text = util.retrieve_text(scratch_text_name_root) except errors.Tesser_General_Exception: if graceful_errors: im = Image.open(filename) text = image_to_string(im, cleanup) else: raise finally: if cleanup: util.perform_cleanup(scratch_image_name, scratch_text_name_root) return text if __name__=='__main__': im = Image.open("/home/oomsys/phototest.tif") text = image_to_string(im) print text try: text = image_file_to_string('fnord.tif', graceful_errors=False) except errors.Tesser_General_Exception, value: print "fnord.tif is incompatible filetype. Try graceful_errors=True" print value text = image_file_to_string('fnord.tif', graceful_errors=True) print "fnord.tif contents:", text text = image_file_to_string('fonts_test.png', graceful_errors=True) print text

    Read the article

  • Error in code of basic game using multiple sprites and surfaceView [on hold]

    - by Khagendra Nath Mahato
    I am a beginner to android and i was trying to make a basic game with the help of an online video tutorial. I am having problem with the multi-sprites and how to use with surfaceview.The application fails launching. Here is the code of the game.please help me. package com.example.killthemall; import java.util.ArrayList; import java.util.List; import java.util.Random; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Bundle; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; public class Game extends Activity { KhogenView View1; @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); while(true){ try { OurThread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }} } Thread OurThread; int herorows = 4; int herocolumns = 3; int xpos, ypos; int xspeed; int yspeed; int herowidth; int widthnumber = 0; int heroheight; Rect src; Rect dst; int round; Bitmap bmp1; // private Bitmap bmp1;//change name public List<Sprite> sprites = new ArrayList<Sprite>() { }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); View1 = new KhogenView(this); setContentView(View1); sprites.add(createSprite(R.drawable.image)); sprites.add(createSprite(R.drawable.bad1)); sprites.add(createSprite(R.drawable.bad2)); sprites.add(createSprite(R.drawable.bad3)); sprites.add(createSprite(R.drawable.bad4)); sprites.add(createSprite(R.drawable.bad5)); sprites.add(createSprite(R.drawable.bad6)); sprites.add(createSprite(R.drawable.good1)); sprites.add(createSprite(R.drawable.good2)); sprites.add(createSprite(R.drawable.good3)); sprites.add(createSprite(R.drawable.good4)); sprites.add(createSprite(R.drawable.good5)); sprites.add(createSprite(R.drawable.good6)); } private Sprite createSprite(int image) { // TODO Auto-generated method stub bmp1 = BitmapFactory.decodeResource(getResources(), image); return new Sprite(this, bmp1); } public class KhogenView extends SurfaceView implements Runnable { SurfaceHolder OurHolder; Canvas canvas = null; Random rnd = new Random(); { xpos = rnd.nextInt(canvas.getWidth() - herowidth)+herowidth; ypos = rnd.nextInt(canvas.getHeight() - heroheight)+heroheight; xspeed = rnd.nextInt(10 - 5) + 5; yspeed = rnd.nextInt(10 - 5) + 5; } public KhogenView(Context context) { super(context); // TODO Auto-generated constructor stub OurHolder = getHolder(); OurThread = new Thread(this); OurThread.start(); } @Override public void run() { // TODO Auto-generated method stub herowidth = bmp1.getWidth() / 3; heroheight = bmp1.getHeight() / 4; boolean isRunning = true; while (isRunning) { if (!OurHolder.getSurface().isValid()) continue; canvas = OurHolder.lockCanvas(); canvas.drawRGB(02, 02, 50); for (Sprite sprite : sprites) { if (widthnumber == 3) widthnumber = 0; update(); getdirection(); src = new Rect(widthnumber * herowidth, round * heroheight, (widthnumber + 1) * herowidth, (round + 1)* heroheight); dst = new Rect(xpos, ypos, xpos + herowidth, ypos+ heroheight); canvas.drawBitmap(bmp1, src, dst, null); } widthnumber++; OurHolder.unlockCanvasAndPost(canvas); } } public void update() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (xpos + xspeed <= 0) xspeed = 40; if (xpos >= canvas.getWidth() - herowidth) xspeed = -50; if (ypos + yspeed <= 0) yspeed = 45; if (ypos >= canvas.getHeight() - heroheight) yspeed = -55; xpos = xpos + xspeed; ypos = ypos + yspeed; } public void getdirection() { double angleinteger = (Math.atan2(yspeed, xspeed)) / (Math.PI / 2); round = (int) (Math.round(angleinteger) + 2) % herorows; // Toast.makeText(this, String.valueOf(round), // Toast.LENGTH_LONG).show(); } } public class Sprite { Game game; private Bitmap bmp; public Sprite(Game game, Bitmap bmp) { // TODO Auto-generated constructor stub this.game = game; this.bmp = bmp; } } } Here is the LogCat if it helps.... 08-22 23:18:06.980: D/AndroidRuntime(28151): Shutting down VM 08-22 23:18:06.980: W/dalvikvm(28151): threadid=1: thread exiting with uncaught exception (group=0xb3f6f4f0) 08-22 23:18:06.980: D/AndroidRuntime(28151): procName from cmdline: com.example.killthemall 08-22 23:18:06.980: E/AndroidRuntime(28151): in writeCrashedAppName, pkgName :com.example.killthemall 08-22 23:18:06.980: D/AndroidRuntime(28151): file written successfully with content: com.example.killthemall StringBuffer : ;com.example.killthemall 08-22 23:18:06.990: I/Process(28151): Sending signal. PID: 28151 SIG: 9 08-22 23:18:06.990: E/AndroidRuntime(28151): FATAL EXCEPTION: main 08-22 23:18:06.990: E/AndroidRuntime(28151): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.killthemall/com.example.killthemall.Game}: java.lang.NullPointerException 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.os.Handler.dispatchMessage(Handler.java:99) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.os.Looper.loop(Looper.java:130) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.main(ActivityThread.java:3683) 08-22 23:18:06.990: E/AndroidRuntime(28151): at java.lang.reflect.Method.invokeNative(Native Method) 08-22 23:18:06.990: E/AndroidRuntime(28151): at java.lang.reflect.Method.invoke(Method.java:507) 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:638) 08-22 23:18:06.990: E/AndroidRuntime(28151): at dalvik.system.NativeStart.main(Native Method) 08-22 23:18:06.990: E/AndroidRuntime(28151): Caused by: java.lang.NullPointerException 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.example.killthemall.Game$KhogenView.<init>(Game.java:96) 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.example.killthemall.Game.onCreate(Game.java:58) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 08-22 23:18:06.990: E/AndroidRuntime(28151): ... 11 more 08-22 23:18:18.050: D/AndroidRuntime(28191): Shutting down VM 08-22 23:18:18.050: W/dalvikvm(28191): threadid=1: thread exiting with uncaught exception (group=0xb3f6f4f0) 08-22 23:18:18.050: I/Process(28191): Sending signal. PID: 28191 SIG: 9 08-22 23:18:18.050: D/AndroidRuntime(28191): procName from cmdline: com.example.killthemall 08-22 23:18:18.050: E/AndroidRuntime(28191): in writeCrashedAppName, pkgName :com.example.killthemall 08-22 23:18:18.050: D/AndroidRuntime(28191): file written successfully with content: com.example.killthemall StringBuffer : ;com.example.killthemall 08-22 23:18:18.050: E/AndroidRuntime(28191): FATAL EXCEPTION: main 08-22 23:18:18.050: E/AndroidRuntime(28191): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.killthemall/com.example.killthemall.Game}: java.lang.NullPointerException 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.os.Handler.dispatchMessage(Handler.java:99) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.os.Looper.loop(Looper.java:130) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.main(ActivityThread.java:3683) 08-22 23:18:18.050: E/AndroidRuntime(28191): at java.lang.reflect.Method.invokeNative(Native Method) 08-22 23:18:18.050: E/AndroidRuntime(28191): at java.lang.reflect.Method.invoke(Method.java:507) 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:638) 08-22 23:18:18.050: E/AndroidRuntime(28191): at dalvik.system.NativeStart.main(Native Method) 08-22 23:18:18.050: E/AndroidRuntime(28191): Caused by: java.lang.NullPointerException 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.example.killthemall.Game$KhogenView.<init>(Game.java:96) 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.example.killthemall.Game.onCreate(Game.java:58) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 08-22 23:18:18.050: E/AndroidRuntime(28191): ... 11 more

    Read the article

  • selective backup script in bash

    - by Sake
    Hi, I've been using this simple command (that's all I can do :) to backup the whole tree from my user data in NAS server for a year. cp -r /STORAGE /BACKUP-STORAGE/YYYY-MM-DD Unfortunately, after a year of service. My user start filling the spaces with lot of photo and cliparts (jpg, gif, bmp) And that start to make my backup process get much slower. The space is also a big issue. Now I no longer have enough space for a week-long daily backup set. I think I want to change from backup everything to backup only non-image data. How can I exclude jpg, gif, and bmp from the backup ? It's quite easy with DOS XCOPY command, but I really have no idea how to do that in bash. Thanks

    Read the article

  • android game performance regarding timers

    - by iQue
    Im new to the game-dev world and I have a tendancy to over-simplify my code, and sometimes this costs me alot fo memory. Im using a custom TimerTask that looks like this: public class Task extends TimerTask { private MainGamePanel panel; public Task(MainGamePanel panel) { this.panel=panel; } /** * When the timer executes, this code is run. */ public void run() { panel.createEnemies(); } } this task calls this method from my view: public void createEnemies() { Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.female); if(enemyCounter < 24){ enemies.add(new Enemy(bmp, this)); } enemyCounter++; } Since I call this in the onCreate-method instead of in my views contructor (because My enemies need to get width and height of view). Im wondering if this will work when I have multiple levels in game (start a new intent). And if this kind of timer really is the best way to add a delay between the spawning-time of my enemies performance-wise. adding code for my timer if any1 came here cus they dont understand timers: private Timer timer1 = new Timer(); private long delay1 = 5*1000; // 5 sec delay public void surfaceCreated(SurfaceHolder holder) { timer1.schedule(new Task(this), 0, delay1); //I call my timer and add the delay thread.setRunning(true); thread.start(); }

    Read the article

  • How to check that image sizes are ok or not

    - by Goran
    I am having many image files in one folder. Mostly there are jpg, but some png, bmp, gif, tif also (but jpg is most important if others are not possible). There are also many xml files in same folder with same names as image files are having. So there is something like this: 1.jpg, 1.xml, a.png, a.xml, 3g.bmp, 3g.xml... All xml files are having only 1 line: <IMGRES WIDTH="1234" HEIGHT="567" /> (of course numbers are not same). I am looking for some easy way to check all image sizes and confirm if they are same as in xml or not. So I want output like: imagename, xmlwidth x xmlheight, realwidth x realheight, match/error Is this possible in only Windows with no other software installed?

    Read the article

  • tar - exclude certain files

    - by Alan
    I wish to tar all files in a directory and its subdirectories that do NOT end in .jpg, .bmp, .gif, or png. So, given the following folders and files: foo/file.txt foo/file.gif foo/bar/file foo/bar/image.jpg I want to tar only the files file.txt and file. file.gif and image.jpg should be ignored. I would also like to maintain the folder structure. My first thought was to pipe the results of the find command in conjunction with grep -v ".jpg|.gif|.bmp.png" to a text file, and then use the tar include argument to feed it that list of files. However, the results of the grepped find command also contain directories (in the example above, it would be "foo" and "foo/bar"), and when a directory is fed to tar, it includes all files in that directory, so I would end up with a tar file containing all of the files--not what I want. Is there any way to prevent find from outputting directories? Is there a far easier way to approach this?

    Read the article

  • how to solve ArrayList outOfBoundsExeption?

    - by iQue
    Im getting: 09-02 17:15:39.140: E/AndroidRuntime(533): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1 09-02 17:15:39.140: E/AndroidRuntime(533): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) when Im killing enemies using this method: private void checkCollision() { Rect h1 = happy.getBounds(); for (int i = 0; i < enemies.size(); i++) { for (int j = 0; j < bullets.size(); j++) { Rect b1 = bullets.get(j).getBounds(); Rect e1 = enemies.get(i).getBounds(); if (b1.intersect(e1)) { enemies.get(i).damageHP(5); bullets.remove(j); Log.d("TAG", "HERE: LOLTHEYTOUCHED"); } if (h1.intersect(e1)){ happy.damageHP(5); } if(enemies.get(i).getHP() <= 0){ enemies.remove(i); } if(happy.getHP() <= 0){ //end-screen !!!!!!! } } } } using this ArrayList: private ArrayList<Enemy> enemies = new ArrayList<Enemy>(); and adding to array like this: public void createEnemies() { Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.female); if (enemyCounter < 24) { enemies.add(new Enemy(bmp, this, controls)); } enemyCounter++; } I dont really understand what the problem is, Ive been looking around for a while but cant really find anything that helps me. If you know or if you can link me someplace where they have a solution for a similar problem Ill be a very happy camper! Thanks for ur time.

    Read the article

  • WPF: Updating visibility of controls not updating the screen

    - by Brad McBride
    I will preface this by stating that I am new to WPF programming and may be making multiple errors. Any insight that can be provided to help me improve in my skills are greatly appreciated. I am working with a WPF application and am looping through a list of objects that contain properties that describe a document that should be built on the fly and automatically printed. I am attempting to display a small grid in the interface that shows the document being built before it is printed. This serves two purposes: one, it allows the user to see work being done by the application. Two, it renders the items on the screen so that I can then have something to actually print since WPF appears to not be able to load an image for printing dynamicaly without displaying it on the screen. In my code, I am setting the various elements in the grid and setting the visibility to visible. However, the UI is not updating and the printed document doesn't look as intended since the image never shows up on the screen. Here is the XAML that I have set up <Grid x:Name="LayoutRoot" Background="Black"> <Grid Name="previewGrid" Grid.Row="1" Grid.Column="1" Background="White" Visibility="Hidden"> <Canvas Name="pageCanvas" HorizontalAlignment="Center" VerticalAlignment="Center"> <Grid Name="pageGrid" Width="163" Height="211"> <Grid.ColumnDefinitions> <ColumnDefinition Width="81.5"></ColumnDefinition> <ColumnDefinition Width="81.5"></ColumnDefinition> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Name="copyright" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Bottom"></TextBlock> <Image Name="pageImage" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center"></Image> </Grid> </Canvas> .....canvas for pages 2-4 not shown but structure is the same as for pageGrid..... </Grid> </Grid> </Window> Here is the code behind that is supposed to set the elements. previewGrid.Visibility = Windows.Visibility.Visible pageURI = New Uri(pageCollection(i).iamgeURL, UriKind.Absolute) pageGrid.Visibility = Windows.Visibility.Visible bmp.BeginInit() bmp.StreamSource = getCachedURLStream(cardURI) bmp.EndInit() pageImage.Source = bmp copyright.Text = copyrightText cardPreviewGrid.UpdateLayout() ' More code that prints the visual element pageGrid previewGrid.Visibility = Windows.Visibility.Hidden The code in codebehind loops through a number of times depending on how many different documents the user prints. Basically it builds a visual element for a page, prints an XPS version of it and then builds the next page and prints it, etc. Once all pages have been processed, the job is actually sent to the printer. The only purpose of this application is to let the user print these documents so there is not other task that they can do in the application while the documents print. I thought that putting this task in a background thread would help to update the UI but since I am trying to manipulate items directly on the UI thread it would appear that this option won't work for me. What am I doing wrong here and how can I improve the code so that I can get the behavior that I am trying to achieve?

    Read the article

  • [C] Texture management / pointer question

    - by ndg
    I'm working on a texture management and animation solution for a small side project of mine. Although the project uses Allegro for rendering and input, my question mostly revolves around C and memory management. I wanted to post it here to get thoughts and insight into the approach, as I'm terrible when it comes to pointers. Essentially what I'm trying to do is load all of my texture resources into a central manager (textureManager) - which is essentially an array of structs containing ALLEGRO_BITMAP objects. The textures stored within the textureManager are mostly full sprite sheets. From there, I have an anim(ation) struct, which contains animation-specific information (along with a pointer to the corresponding texture within the textureManager). To give you an idea, here's how I setup and play the players 'walk' animation: createAnimation(&player.animations[0], "media/characters/player/walk.png", player.w, player.h); playAnimation(&player.animations[0], 10); Rendering the animations current frame is just a case of blitting a specific region of the sprite sheet stored in textureManager. For reference, here's the code for anim.h and anim.c. I'm sure what I'm doing here is probably a terrible approach for a number of reasons. I'd like to hear about them! Am I opening myself to any pitfalls? Will this work as I'm hoping? anim.h #ifndef ANIM_H #define ANIM_H #define ANIM_MAX_FRAMES 10 #define MAX_TEXTURES 50 struct texture { bool active; ALLEGRO_BITMAP *bmp; }; struct texture textureManager[MAX_TEXTURES]; typedef struct tAnim { ALLEGRO_BITMAP **sprite; int w, h; int curFrame, numFrames, frameCount; float delay; } anim; void setupTextureManager(void); int addTexture(char *filename); int createAnimation(anim *a, char *filename, int w, int h); void playAnimation(anim *a, float delay); void updateAnimation(anim *a); #endif anim.c void setupTextureManager() { int i = 0; for(i = 0; i < MAX_TEXTURES; i++) { textureManager[i].active = false; } } int addTextureToManager(char *filename) { int i = 0; for(i = 0; i < MAX_TEXTURES; i++) { if(!textureManager[i].active) { textureManager[i].bmp = al_load_bitmap(filename); textureManager[i].active = true; if(!textureManager[i].bmp) { printf("Error loading texture: %s", filename); return -1; } return i; } } return -1; } int createAnimation(anim *a, char *filename, int w, int h) { int textureId = addTextureToManager(filename); if(textureId > -1) { a->sprite = textureManager[textureId].bmp; a->w = w; a->h = h; a->numFrames = al_get_bitmap_width(a->sprite) / w; printf("Animation loaded with %i frames, given resource id: %i\n", a->numFrames, textureId); } else { printf("Texture manager full\n"); return 1; } return 0; } void playAnimation(anim *a, float delay) { a->curFrame = 0; a->frameCount = 0; a->delay = delay; } void updateAnimation(anim *a) { a->frameCount ++; if(a->frameCount >= a->delay) { a->frameCount = 0; a->curFrame ++; if(a->curFrame >= a->numFrames) { a->curFrame = 0; } } }

    Read the article

  • C# slowdown while creating a bitmap - calculating distances from a large List of places for each pixel

    - by user576849
    I'm creating a graphic of the glow of lights above a geographic location based upon Walkers Law: Skyglow=0.01*Population*DistanceFromCenter^-2.5 I have a CSV file of places with 66,000 records using 5 fields (id,name,population,latitude,longitude), parsed on the FormLoad event and stored it in: List<string[]> placeDataList Then I set up nested loops to fill in a bitmap using SetPixel. For each pixel on the bitmap, which represents a coordinate on a map (latitude and longitude), the program loops through placeDataList – calculating the distance from that coordinate (pixel) to each place record. The distance (along with population) is used in a calculation to find how much cumulative sky glow is contributed to the coordinate from each place record. So, for every pixel, 66,000 distance calculations must be made. The problem is, this is predictably EXTREMELY slow – on the order of one line of pixels per 30 seconds or so on a 320 pixel wide image. This is unrelated to SetPixel, which I know is also slow, because the speed is similarly slow when adding the distance calculation results to an array. I don’t actually need to test all 66,000 records for every pixel, only the records within 150 miles (i.e. no skyglow is contributed to a coordinate from a small town 3000 miles away). But to find which records are within 150 miles of my coordinate I would still need to loop through all the records for each pixel. I can't use a smaller number of records because all 66,000 places contribute to skyglow for SOME coordinate in my map as it loops. This seems like a Catch-22, so I know there must be a better method out there. Like I mentioned, the slowdown is related to how many calculations I’m making per pixel, not anything to do with the bitmap. Any suggestions? private void fillPixels(int width) { Color pixelColor; int pixel_w = width; int pixel_h = (int)Math.Floor((width * 0.424088664)); Bitmap bmp = new Bitmap(pixel_w, pixel_h); for (int i = 0; i < pixel_h; i++) for (int j = 0; j < pixel_w; j++) { pixelColor = getPixelColor(i, j); bmp.SetPixel(j, i, pixelColor); } bmp.Save("Nightfall", System.Drawing.Imaging.ImageFormat.Jpeg); pictureBox1.Image = bmp; MessageBox.Show("Done"); } private Color getPixelColor(int height, int width) { int c; double glow,d,cityLat,cityLon,cityPop; double testLat, testLon; int size_h = (int)Math.Floor((size_w * 0.424088664)); ; testLat = (height * (24.443136 / size_h)) + 24.548874; testLon = (width * (57.636853 / size_w)) -124.640767; glow = 0; for (int i = 0; i < placeDataList.Count; i++) { cityPop=Convert.ToDouble(placeDataList[i][2]); cityLat=Convert.ToDouble(placeDataList[i][3]); cityLon=Convert.ToDouble(placeDataList[i][4]); d = distance(testLat, testLon, cityLat, cityLon,"M"); if(d<150) glow = glow+(0.01 * cityPop * Math.Pow(d, -2.5)); } if (glow >= 1) glow=1; c = (int)Math.Ceiling(glow * 255); return Color.FromArgb(c, c, c); }

    Read the article

  • Space invaders clone not moving properly

    - by ThePlan
    I'm trying to make a basic space invaders clone in allegro 5, I've got my game set up, basic events and such, here is the code: #include <allegro5/allegro.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_primitives.h> #include <allegro5/allegro_font.h> #include <allegro5/allegro_ttf.h> #include "Entity.h" // GLOBALS ========================================== const int width = 500; const int height = 500; const int imgsize = 3; bool key[5] = {false, false, false, false, false}; bool running = true; bool draw = true; // FUNCTIONS ======================================== void initSpaceship(Spaceship &ship); void moveSpaceshipRight(Spaceship &ship); void moveSpaceshipLeft(Spaceship &ship); void initInvader(Invader &invader); void moveInvaderRight(Invader &invader); void moveInvaderLeft(Invader &invader); void initBullet(Bullet &bullet); void fireBullet(); void doCollision(); void updateInvaders(); void drawText(); enum key_t { UP, DOWN, LEFT, RIGHT, SPACE }; enum source_t { INVADER, DEFENDER }; int main(void) { if(!al_init()) { return -1; } Spaceship ship; Invader invader; Bullet bullet; al_init_image_addon(); al_install_keyboard(); al_init_font_addon(); al_init_ttf_addon(); ALLEGRO_DISPLAY *display = al_create_display(width, height); ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); ALLEGRO_TIMER *timer = al_create_timer(1.0 / 60); ALLEGRO_BITMAP *images[imgsize]; ALLEGRO_FONT *font1 = al_load_font("arial.ttf", 20, 0); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); images[0] = al_load_bitmap("defender.bmp"); images[1] = al_load_bitmap("invader.bmp"); images[2] = al_load_bitmap("explosion.bmp"); al_convert_mask_to_alpha(images[0], al_map_rgb(0, 0, 0)); al_convert_mask_to_alpha(images[1], al_map_rgb(0, 0, 0)); al_convert_mask_to_alpha(images[2], al_map_rgb(0, 0, 0)); initSpaceship(ship); initBullet(bullet); initInvader(invader); al_start_timer(timer); while(running) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_TIMER) { draw = true; if(key[RIGHT] == true) moveSpaceshipRight(ship); if(key[LEFT] == true) moveSpaceshipLeft(ship); } else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) running = false; else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: running = false; break; case ALLEGRO_KEY_LEFT: key[LEFT] = true; break; case ALLEGRO_KEY_RIGHT: key[RIGHT] = true; break; case ALLEGRO_KEY_SPACE: key[SPACE] = true; break; } } else if(ev.type == ALLEGRO_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_LEFT: key[LEFT] = false; break; case ALLEGRO_KEY_RIGHT: key[RIGHT] = false; break; case ALLEGRO_KEY_SPACE: key[SPACE] = false; break; } } if(draw && al_is_event_queue_empty(event_queue)) { draw = false; al_draw_bitmap(images[0], ship.pos_x, ship.pos_y, 0); al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); } } al_destroy_font(font1); al_destroy_event_queue(event_queue); al_destroy_timer(timer); for(int i = 0; i < imgsize; i++) al_destroy_bitmap(images[i]); al_destroy_display(display); } // FUNCTION LOGIC ====================================== void initSpaceship(Spaceship &ship) { ship.lives = 3; ship.speed = 2; ship.pos_x = width / 2; ship.pos_y = height - 20; } void initInvader(Invader &invader) { invader.health = 100; invader.count = 40; invader.speed = 0.5; invader.pos_x = 300; invader.pos_y = 300; } void initBullet(Bullet &bullet) { bullet.speed = 10; } void moveSpaceshipRight(Spaceship &ship) { ship.pos_x += ship.speed; if(ship.pos_x >= width) ship.pos_x = width-30; } void moveSpaceshipLeft(Spaceship &ship) { ship.pos_x -= ship.speed; if(ship.pos_x <= 0) ship.pos_x = 0+30; } However it's not behaving the way I want it to behave, in fact the behavior for the ship movement is un-normal. Basically I specified that the ship only moves when the right/left key is down, however the ship is moving constantly to the direction of the key pressed, it never stops although it should only move while my key is down. Even more weird behavior, when I press the opposite key the ship completely stops no matter what else I press. What's wrong with the code? Why does the ship move constantly even after I specified it only moves when a key is down?

    Read the article

  • Android 2.1 View's getDrawingCache() method always returns null

    - by Impression
    Hello, I'm working with Android 2.1 and have the following problem: Using the method View.getDrawingCache() always returns null. Example code: public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final View view = findViewById(R.id.ImageView01); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); final Bitmap bmp = view.getDrawingCache(); System.out.println(bmp); } I've already tried different ways to configure the View object for generating the drawing cache (e.g. View.setWillNotDraw(boolean) and View.setWillNotCacheDrawing(boolean)), but nothing works. What is the right ways, or what do I wrong?

    Read the article

  • Screen Capture Under Win7 of JOGL Applet

    - by binarybug
    Hi I'm trying to take a screen shot of an applet running inside a browser. The applet is using JOGL (OpenGL for Java) to display 3D models. (1) The screen shots always come out either black or white.The current solution uses the usual GDI calls. Screen shots of applets not running OpenGL are fine. A few examples of JOGL apps can be found here https://jogl-demos.dev.java.net/ (2) Another thing I'm trying to achieve is to get the scrollable area inside the screen shot as well. I found this code on the internet which works fine except for the 2 issues mentioned above. import win32gui as wg import win32ui as wu import win32con def copyBitMap(hWnd, fname): wg.SetForegroundWindow(hWnd) cWnd = wu.CreateWindowFromHandle(hWnd) rect = cWnd.GetClientRect() (x,y) = (rect[2] - rect[0], rect[3] - rect[1]) hsrccDc = wg.GetDC(hWnd) hdestcDc = wg.CreateCompatibleDC(hsrccDc) hdestcBm = wg.CreateCompatibleBitmap(hsrccDc, x, y) wg.SelectObject(hdestcDc, hdestcBm.handle) wg.BitBlt(hdestcDc, 0, 0, x, y, hsrccDc, rect[0], rect[1], win32con.SRCCOPY) destcDc = wu.CreateDCFromHandle(hdestcDc) bmp = wu.CreateBitmapFromHandle(hdestcBm.handle) bmp.SaveBitmapFile(destcDc, fname)

    Read the article

  • Image scaling in C

    - by Ganesh
    Hi, I am designing a jpeg to bmp decoder which scales the image. I have been supplied with the source code for the decoder so my actual work is to design a scaler . I do not know where to begin. I have scouted the internet for the various scaling algorithms but am not sure where to introduce the scaling. So should I do the the scaling after the image is converted into bmp or should I do this during the decoding at the MCU level. am confused :( If you guys have some information to help me out, its appreciated. any material to read, source code to analyse etc....

    Read the article

  • Using Bitmap.LockBits and Marshal.Copy in IronPython not changing image as expected

    - by Leonard H Martin
    Hi all, I have written the following IronPython code: import clr clr.AddReference("System.Drawing") from System import * from System.Drawing import * from System.Drawing.Imaging import * originalImage = Bitmap("Test.bmp") def RedTint(bitmap): bmData = bitmap.LockBits(Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb) ptr = bmData.Scan0 bytes = bmData.Stride * bitmap.Height rgbValues = Array.CreateInstance(Byte, bytes) Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes) for i in rgbValues[::3]: i = 255 Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes) bitmap.UnlockBits(bmData) return bitmap newPic = RedTint(originalImage) newPic.Save("New.bmp") Which is my interpretation of this MSDN code sample: http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx except that I am saving the altered bitmap instead of displaying it in a Form. The code runs, however the newly saved bitmap is an exact copy of the original image with no sign of any changes having occurred (it's supposed to create a red tint). Could anyone advise what's wrong with my code? The image I'm using is simply a 24bpp bitmap I created in Paint (it's just a big white rectangle!), using IronPython 2.6 and on Windows 7 (x64) with .Net Framework 3.5 SP1 installed.

    Read the article

  • How can I overwrite a System.Drawing.Bitmap onto an existing GDI bitmap?

    - by MusiGenesis
    If I have a .Net Bitmap, I can create from it a GDI bitmap by calling the Bitmap's GetHbitmap() method. Bitmap bmp = new Bitmap(100, 100); IntPtr gdiBmp = bmp.GetHbitmap(); This works fine, but every time you call GetHbitmap, Windows has to allocate new memory for the object that gdiBmp references. What I'd like to do - if possible - is write a function (I know PInvoke will be necessary here) that also generates a GDI bitmap copy of a Bitmap, but that uses an existing object instead of allocating a new one. So it would look something like this (if it were an extension method of Bitmap): //void OverwriteHbitmap(IntPtr gdi) Bitmap bmp1 = new Bitmap(100, 100); IntPtr gdi1 = bmp1.GetHbitmap(); Bitmap bmp2 = new Bitmap(100, 100); bmp2.OverwriteHbitmap(gdi1); How can I do this? I assume I'll need to know the structure of a GDI bitmap, and probably I can use LockBits and BitmapData for this, but I'm not sure exactly how.

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >