Search Results

Search found 1375 results on 55 pages for 'bitmap'.

Page 22/55 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • Replacing a colour/colours in a movieclip with different colours?

    - by Oli
    I am trying to take a movieclip of a character and change the colour of their clothes. The character is comprised of vectors. So far I have semi-sucessfully used this method: stop the movieclip take the bitmap data from the current frame use threshold to replace the colour store the resulting bitmap data in an array add an onenterframe function - clear the current frame and add the bitmap data from the processed data in the array So - this works pretty well. Each frame is only processed once at the beginning and then the write to the movieclip is very quick. However! As the replacement is being performed on a bitmap there is an amount of aliasing that takes place to remove jaggies/pixelation. This produces colours that are not matched using threshold. So the main colour is replaced correctly but it is surrounded by a halo of mixed colours :( I am sure there should be a better way to do this. Any ideas or answers would be greatly apreciated - Thanks.

    Read the article

  • Memory leak while using emoticons on CRichEditCtrl

    - by Jorg B Jorge
    I'm developing a text editor class (for a chat application) based on CRichEditCtrl (MFC) with emoticon support. After i load the emoticon's bitmap, I use the function OleCreateStaticFromData to insert it into CRichEditCtrl. After that i just delete the bitmap object allocated by myself. I can verify (using a GDIView utility) that all resources i allocate have been properly released. This works perfectly: the bitmap (emoticon) is drawn on the CRichEditCtrl window and is handled just like a character. My problem is that I don't know how to deallocate the memory (internal) allocated by OleCreateStaticFromData to manage the bitmap (emoticon). The memory allocated for any emoticon used is never released, even if i delete the CRichEditCtrl object. I'd like to know how to fix that issue. Is that a MFC's issue or i'm doing something wrong ? Thx.

    Read the article

  • Is Graphics.DrawImage asynchronous?

    - by Roy
    Hi all, I was just wondering, is Graphics.DrawImage() asynchronous? I'm struggling with a thread safety issue and can't figure out where the problem is. if i use the following code in the GUI thread: protected override void OnPaint(PaintEventArgs e) { lock (_bitmapSyncRoot) { e.Graphics.DrawImage(_bitmap, _xPos, _yPos); } } And have the following code in a separate thread: private void RedrawBitmapThread() { Bitmap newBitmap = new Bitmap(_width, _height); // Draw bitmap // Bitmap oldBitmap = null; lock (_bitmapSyncRoot) { oldBitmap = _bitmap; _bitmap = newBitmap; } if (oldBitmap != null) { oldBitmap.Dispose(); } Invoke(Invalidate); } Could that explain an accessviolation exception? The code is running on a windows mobile 6.1 device with compact framework 3.5.

    Read the article

  • Drawing random circles

    - by ViktorC
    I am trying to draw a cupola circles at random positions in an Android application. I draw them on a bitmap and then draw that bitmap on the canvas. This is the function where a draw the circles: private void drawRandomCircles(int numOfCircles) { Canvas c = new Canvas(b); Paint cPaint = new Paint; cPaitn.setColor(Color.RED); for(int i = 0; i < numOfCircles; i++) { int x = Math.Random % 100; int y = Math.Random % 100; c.drawCircle(x, y, 20, cPaint) } } The Bitmap b is global. And after calling this function I just draw the bitmap in the onDraw method. Now the problem is that I only get one circle drawn on the screen, no matter the size of numOfCircles. Any clue what is happening here?

    Read the article

  • VB.NET trying simple captcha

    - by Pride Grimm
    I'm trying to write a simple captcha program in vb.net. I'm just wanting to make an image from random numbers and display it, check the answer, and then proceed. I'm pretty new to vb.net, so I found some code to generate the information. I will cite the owner when I find it again (http://www.knowlegezone.com/80/article/Technology/Software/Asp-Net/Simple-ASP-NET-CAPTCHA-Tutorial) This is in the onload() of default2.aspx Public Sub returnNumer() Dim num1 As New Random Dim num2 As New Random Dim numQ1 As Integer Dim numQ2 As Integer Dim QString As String numQ1 = num1.Next(10, 15) numQ2 = num2.Next(17, 31) QString = numQ1.ToString + " + " + numQ2.ToString + " = " Session("answer") = numQ1 + numQ2 Dim bitmap As New Bitmap(85, 35) Dim Grfx As Graphics = Graphics.FromImage(bitmap) Dim font As New Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel) Dim Rect As New Rectangle(0, 0, 100, 50) Grfx.FillRectangle(Brushes.Brown, Rect) Grfx.DrawRectangle(Pens.PeachPuff, Rect) ' Border Grfx.DrawString(QString, font, Brushes.Azure, 0, 0) Response.ContentType = "Image/jpeg" bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg) bitmap.Dispose() Grfx.Dispose() End Sub So I put this in a separate page, like this This all works find and dandy, but when I get the answer from the session like this Dim literal As String = Convert.ToString(Session("answer")) It's always one behind. So if The images adds to 32, the answer in session isn't 32. But after a refresh (and a new image) the session("answer") will be 32. Is there a way to refresh the session on page 1, after the default2.aspx loads? Is there a better way to do this? I though about trying to run the code all on one page, and trying to set the src of and image to returnNumber(), but I need a bit of help on that one.

    Read the article

  • Mask image does not appear on the screen

    - by Ponty
    I have imported to the library two images and have given them the custom class names MaskImage and MaskedImage. Then i write the code: package { import flash.display.*; public class MaskDemo extends Sprite { // Properties private var sprMaskedImage:Sprite; private var sprMaskImage:Sprite; private var bmMaskedImage:Bitmap; private var bmMaskImage:Bitmap; // Constructor public function MaskDemo() { do_magic(); } // Methods private function do_magic():void { bmMaskedImage = new Bitmap(new MaskedImage(0, 0)); bmMaskImage = new Bitmap(new MaskImage(0, 0)); sprMaskedImage = new Sprite(); sprMaskedImage.addChild(bmMaskedImage); sprMaskImage = new Sprite(); sprMaskImage.addChild(bmMaskImage); sprMaskedImage.mask = sprMaskImage; this.addChild(sprMaskImage); } } } But it does not appear anything on the display. Any ideas why is happening that?

    Read the article

  • GDI+ DrawImage function

    - by ET
    There is something I am missing. Say I have the following code: private Bitmap source = new Bitmap (some_stream); Bitmap bmp = new Bitmap(100,100); Rectangle newRect = new Rectangle(0, 0, bmp.Width, bmp.Height); Rectangle toZoom= new Rectangle(0, 0, 10, 10); Graphics g = Graphics.FromImage(bmp); g.DrawImage(source, newRect, toZoom, GraphicsUnit.Pixel); My goal is to zoom-in the 10x10 pixels on the top left corner of the source picture. After I created the graphics object g and called DrawImage: the requested rectangle (toZoom) will be copied to bmp, or will it be displayed on the screen? I am a bit confused, can somebody please clarify?

    Read the article

  • WCF/REST Get image into picturebox?

    - by Garrith
    So I have wcf rest service which succesfuly runs from a console app, if I navigate to: http://localhost:8000/Service/picture/300/400 my image is displayed note the 300/400 sets the width and height of the image within the body of the html page. The code looks like this: namespace WcfServiceLibrary1 { [ServiceContract] public interface IReceiveData { [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "picture/{width}/{height}")] Stream GetImage(string width, string height); } public class RawDataService : IReceiveData { public Stream GetImage(string width, string height) { int w, h; if (!Int32.TryParse(width, out w)) { w = 640; } // Handle error if (!Int32.TryParse(height, out h)) { h = 400; } Bitmap bitmap = new Bitmap(w, h); for (int i = 0; i < bitmap.Width; i++) { for (int j = 0; j < bitmap.Height; j++) { bitmap.SetPixel(i, j, (Math.Abs(i - j) < 2) ? Color.Blue : Color.Yellow); } } MemoryStream ms = new MemoryStream(); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Position = 0; WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg"; return ms; } } } What I want to do now is use a client application "my windows form app" and add that image into a picturebox. Im abit stuck as to how this can be achieved as I would like the width and height of the image from my wcf rest service to be set by the width and height of the picturebox. I have tryed this but on two of the lines have errors and im not even sure if it will work as the code for my wcf rest service seperates width and height with a "/" if you notice in the url. string uri = "http://localhost:8080/Service/picture"; private void button1_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.AppendLine("<picture>"); sb.AppendLine("<width>" + pictureBox1.Image.Width + "</width>"); // the url looks like this http://localhost:8080/Service/picture/300/400 when accessing the image so I am trying to set this here sb.AppendLine("<height>" + pictureBox1.Image.Height + "</height>"); sb.AppendLine("</picture>"); string picture = sb.ToString(); byte[] getimage = Encoding.UTF8.GetBytes(picture); // not sure this is right HttpWebRequest req = WebRequest.Create(uri); //cant convert webrequest to httpwebrequest req.Method = "GET"; req.ContentType = "image/jpg"; req.ContentLength = getimage.Length; MemoryStream reqStrm = req.GetRequestStream(); //cant convert IO stream to IO Memory stream reqStrm.Write(getimage, 0, getimage.Length); reqStrm.Close(); HttpWebResponse resp = req.GetResponse(); // cant convert web respone to httpwebresponse MessageBox.Show(resp.StatusDescription); pictureBox1.Image = Image.FromStream(reqStrm); reqStrm.Close(); resp.Close(); } So just wondering if some one could help me out with this futile attempt at adding a variable image size from my rest service to a picture box on button click. This is the host app aswell: namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(RawDataService), new Uri(baseAddress)); host.AddServiceEndpoint(typeof(IReceiveData), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); host.Open(); Console.WriteLine("Host opened"); Console.ReadLine();

    Read the article

  • PNG Textures not loading on HTC desire

    - by Matthew Tatum
    Hi I'm developing a game for android using OpenGL es and have hit a problem: My game loads fine in the emulator (windows xp and vista from eclipse), it also loads fine on a T-Mobile G2 (HTC Hero) however when I load it on my new HTC Desire none of the textures appear to load correctly (or at all). I'm suspecting the BitmapFactory.decode method although I have no evidence that that is the problem. All of my textures are power of 2 and JPG textures seem to load (although they don't look great quality) but anything that is GIF or PNG just doesn't load at all except for a 2x2 red square which loads fine and one texture that maps to a 3d object but seems to fill each triangle of the mesh with the nearest colour). This is my code for loading images: AssetManager am = androidContext.getAssets(); BufferedInputStream is = null; try { is = new BufferedInputStream(am.open(fileName)); Bitmap bitmap; bitmap = BitmapFactory.decodeStream(is); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } catch(IOException e) { Logger.global.log(Level.SEVERE, e.getLocalizedMessage()); } finally { try { is.close(); } catch(Exception e) { // Ignore. } } thanks

    Read the article

  • Thumbnail image saved with worse quality on Windows Server 2003

    - by Angelo
    Hello, In asp.net 2.0 application I am trying to create thumbnails from uploaded images. However when I test the application on my PC under Windows7 it works fine, but on the real Windows 2003 Server the resized image has worse quality. Where this difference could come from? Different JPEG codec or what, if Yes how it can be updated on Win 2003 Server? Thanks! Here is the code: Resize of the Image: Bitmap newBmp = new Bitmap(imgWidth, imgHeight, PixelFormat.Format24bppRgb); newBmp.SetResolution(inputBmp.HorizontalResolution, inputBmp.VerticalResolution); //Create a graphics object attached to the new bitmap Graphics newBmpGraphics = Graphics.FromImage(newBmp); newBmpGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; newBmpGraphics.SmoothingMode = SmoothingMode.HighQuality; newBmpGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality; newBmpGraphics.DrawImage(inputBmp, new Rectangle(0, 0, imgWidth, imgHeight), new Rectangle(0, 0, inputBmp.Width, inputBmp.Height), GraphicsUnit.Pixel); Save of the Image: System.IO.Stream imgStream = new System.IO.MemoryStream(); //Get the ImageCodecInfo for the desired target format ImageCodecInfo destCodec = FindCodecForType(ImageMimeTypes.JPEG); if (destCodec == null) { //No codec available for that format throw new ArgumentException("The requested format image/jpeg does not have an available codec installed", "destFormat"); } //Create an EncoderParameters collection to contain the //parameters that control the dest format's encoder EncoderParameters destEncParams = new EncoderParameters(1); EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,(long)quality); destEncParams.Param[0] = qualityParam; //Save w/ the selected codec and encoder parameters inputBmp.Save(imgStream, destCodec, destEncParams); Bitmap destBitmap = new Bitmap(imgStream);

    Read the article

  • Error:A generic error occurred in GDI+

    - by sanfra1983
    Hi, I created a web project on the server, and when I upload an image shows me the error Error: A generic error occurred in GDI +. I have read many links on the net that talk about this issue, and although I made the changes, nothing went wrong. I was thinking if the case is not an issue of permissions to folders. In fact I have two folders one inside the other. This is the code to resize the image: public Bitmaps ResizeImage (Stream stream, int? width, int? height) ( System.Drawing.Bitmap bmpOut = null; const int defaultWidth = 800; const int defaultHeight = 600; int width = lnWidth == null? defaultWidth: (int) width; int height = lnHeight == null? defaultHeight: (int) height; try ( LoBMP bitmap = new Bitmap (stream); ImageFormat loFormat = loBMP.RawFormat; decimal lnRatio; lnNewWidth int = 0; lnNewHeight int = 0; if (loBMP.Width <& & lnWidth loBMP.Height <lnHeight) ( loBMP return; ) if (loBMP.Width> loBMP.Height) ( lnRatio = (decimal) lnWidth / loBMP.Width; lnNewWidth = lnWidth; decimal = lnTemp loBMP.Height lnRatio *; lnNewHeight = (int) lnTemp; ) else ( lnRatio = (decimal) lnHeight / loBMP.Height; lnNewHeight = lnHeight; decimal = lnTemp loBMP.Width lnRatio *; lnNewWidth = (int) lnTemp; ) bmpOut = new Bitmap (lnNewWidth, lnNewHeight); Graphics g = Graphics.FromImage (bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle (Brushes.White, 0, 0, lnNewWidth, lnNewHeight); g.DrawImage (loBMP, 0, 0, lnNewWidth, lnNewHeight); loBMP.Dispose (); ) catch ( return null; ) bmpOut return; ) and this is the code that I insert in the codebehind: string filepath = AppDomain.CurrentDomain.BaseDirectory + img_veterinario / "; string = filepathM AppDomain.CurrentDomain.BaseDirectory + img_veterinario / img_veterinarioM; Reseize Reseize R = new (); Bitmap = photosFileOriginal r.ResizeImage (fucasiclinici.PostedFile.InputStream, 400, 400); Bitmap = photosFileMiniatura r.ResizeImage (fucasiclinici.PostedFile.InputStream, 72, 72); String filename = Path.GetFileName (fucasiclinici.PostedFile.FileName); photosFileOriginal.Save (Path.Combine (filepath, filename)); photosFileMiniatura.Save (Path.Combine (filepathM, filename)); Can you help me? Thanks

    Read the article

  • glBlendFunc() with 32-bit RGBA textures

    - by oldSkool
    I have a texture that is semi-transparent with varying opacity at different locations. I have the main texture bitmap, and a mask bitmap. When the program executes, the alpha values from the mask bitmap are loaded into the alpha values of the main texture bitmap. The areas that I want to be transparent have a value of 255 alpha, and the areas that I want to remain totally opaque have values of 0 alpha. There are in-between values also for mid-transparency. I have tried all manner of glBlendFunc() settings, but it is either completely invisible or it acts on the RGB colors of the source texture. Any help out there?

    Read the article

  • Obtaining kerning information

    - by chadb
    How can I obtain kerning information for GDI to then use in GetKerningPairs? The documentation states that The number of pairs in the lpkrnpair array. If the font has more than nNumPairs kerning pairs, the function returns an error. However, I do not know how many pairs to pass in, and I don't see a way to query for it. EDIT I tried to do the following, however, it still gave me 0. Font* myFont = new Font(L"Times New Roman", 10); Bitmap* bitmap = new Bitmap(256, 256, PixelFormat32bppARGB); Graphics* g = new Graphics(bitmap); SelectObject(g->GetHDC(), myFont); //DWORD numberOfKerningPairs = GetKerningPairs( g->GetHDC(), -1, NULL ); DWORD numberOfKerningPairs = GetKerningPairs( g->GetHDC(), INT_MAX, NULL );

    Read the article

  • How can I define an irregular area of the screen and find the closest point to the mouse in that area?

    - by JonathonG
    I'm looking for a method to define an area of the screen that the mouse cannot leave. I have been directed by rob mayoff, the answerer of this question, that I can use a Quartz Event Tap to detect mouse events. This puts me part of the way to the solution to THIS question. I need to define an irregular area of the screen, not just a rectangle, that the mouse cannot leave. I have been researching this and the only idea I can come up with is using a bitmap to define the irregular area, as it will be very oddly shaped. However, I am open to solutions other than using a bitmap. Since this must be done on a Mac, I've determined that I will have to use objective C / Cocoa . I need to know how to define the area and, equally importantly, how to find the closest point in the area to the mouse (so that I can move the mouse to it if the mouse tries to move outside of the area). This is similar to what the restricted area will look like: [edit:] Okay, I've come up with part of the answer to this. If I can do a basic (light-weight) point collision detection on the image mask, I can use a simple algorithm to detect the closest point to the mouse on the black area of the image. I could do this by calculating distance between a pre-defined point (P) inside the black area of the image and the target mouse position (T), taking the midpoint (M), then checking if the midpoint is inside or outside of the shape (black or white, respectively). If M is inside the shape, then move the P to M, otherwise move T to the M, continuously recalculate this until the distance between T and P is 1 pixel or less, then move the mouse to the final calculated position. All of that being said, I still need some way to test the position of the mouse against that same position on the bitmap (assume the bitmap is the same resolution as the monitor), and check if that point is black or white. All of this needs to be done in the background, without this application actually having focus, or the bitmap being visible... is this possible?

    Read the article

  • && operation in actionscript

    - by wcpro
    In the following code the line after the if statement gets run even when "BITMAP" is null. Why is this? public function get BitmapHeight () { if (_bitmapHeight == 0 && BITMAP != null) _bitmapHeight = BITMAP.bitmapData.height; return _bitmapHeight; }

    Read the article

  • e2fsck / resize2fs problems

    - by BlakBat
    I've got 6 drives (each 1.5T, all same model and firmware revision) that are part of a RAID5 array. The RAID5 makes a LVM volume group and a logical group. The latter contains only one ext3 partition. I've recently ran: e2fsck -f /dev/vg03/lv01 && resize2fs -M /dev/vg03/lv01 which exited without an error. Now when I try to mount /dev/vg03/lv01 I get: EXT3-fs error (device dm-0): ext3_check_descriptors: Block bitmap for group 30533 not in group (block 1000532368)! EXT3-fs: group descriptors corrupted! How do I get out of this predicament? This is all the info I can currently give you: fdisk -l /dev/sd[cdefgh] shows (correctly) that they are "Linux raid autodetect" but fdisk now shows: fdisk -l /dev/md0 Disk /dev/md0: 7501.5 GB, 7501495664640 bytes ... Disk identifier: 0x00000000 Disk /dev/md0 doesn't contain a valid partition table (instead of a LVM type partition) fdisk -l /dev/vg03/lv01 Disk /dev/vg03/lv01: 7501.5 GB, 7501491732480 bytes ... Disk identifier: 0x00000000 Disk /dev/vg03/lv01 doesn't contain a valid partition table (instead of a ext3 type partition) I've tried: e2fsck -fy /dev/vg03/lv01 e2fsck 1.41.12 (17-May-2010) e2fsck: Group descriptors look bad... trying backup blocks... Block bitmap for group 30533 is not in group. (block 1000532368) Relocate? yes Inode bitmap for group 30533 is not in group. (block 1000532369) Relocate? yes Pass 1: Checking inodes, blocks, and sizes Relocating group 30533's block bitmap to 1000524246... Error allocating 1 contiguous block(s) in block group 30533 for inode bitmap: Could not allocate block in ext2 filesystem e2fsck: aborted Extra information I can give you: cat /proc/mdstat Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10] md0 : active (auto-read-only) raid5 sdg1[0] sdh1[5] sdf1[4] sde1[3] sdc1[2] sdd1[1] 7325679360 blocks level 5, 128k chunk, algorithm 2 [6/6] [UUUUUU] bitmap: 1/175 pages [4KB], 4096KB chunk unused devices: Lastly, all smartctl tests (short and extendend) showed no errors on any of the disks. Should I try to resize2fs to grow /dev/vg03/lv01 and redo a e2fsck ? Should I cfdisk /dev/md0 and /dev/vg03/lv01 back to their real types? Thanks in advance for all and any help. 2011-09-20 UPDATE I issued the following commands and was able to remount the partition, but by viewing the size (df) of before and after, it seems that 1Tb of data have gone missing. By checking the MD5SUMS (from an old backup) of some files with the "same" files from the remounted partition, some errors have been detected. Commands issued to remount the partition were: dumpe2fs /dev/vg03/lv01 Block count: 1000491435<br /> Block size: 4096<br /> tune2fs -O ^has_journal /dev/vg03/lv01 resize2fs -p /dev/vg03/lv01 dumpe2fs /dev/vg03/lv01 Block count: 1831418880<br /> Block size: 4096<br /> mount -o ro,noatime /dev/vg03/lv01 /mnt/raid OK... but files have been damaged / gone missing.

    Read the article

  • Save and restore multiple layers within a Photoshop action that flattens

    - by SuitCase
    I'm editing comic pages with layers - "background", "foreground", "lineart" and "over lineart". I have a Photoshop action that includes a Mode-Bitmap command, which requires the image to be flattened. I need this part of the action because I use the Halftone Screen method of reducing the greyscale image to bitmap on the "background" layer, creating a certain effect. I am pretty sure there is no filter or anything else that gives the same effect. After the mode is changed to bitmap, my action changes things back to greyscale for further changes. This poses a problem. I only want to do the bitmap mode change on the background layer, and after I do the change I want to restore the layer structure as it was - with the foreground, lineart and over lineart layers back above the now-halftoned background. My current method of saving these layers and restoring them is clumsy. My action is able to automatically save the "foreground" layer by selecting it, cutting it, then pasting it back in after the mode changing is over. But, for the "ink" and "over ink" layers, I have to manually cut these layers, paste them into a new document, and later re-cut and re-paste after running my action. This is so clunky! What I would like to know is if it's possible to set aside my layers in an automated way, and then bring them back in, also in an automated way. An ugly (but functional) solution would be to replicate my actions of creating new documents and pasting them temporarily there, but I don't think Photoshop allows you to do things outside of your current document with an action. It seems to me that the only way to do what I want is to use the "hack" of incorporating the clipboard into the action as a clever hack, but that leaves me stuck as I have two more layers that can't fit onto that same clipboard. Help or suggestions would be appreciated. I can keep on doing it manually, but to have a comprehensive action would save me a ton of time.

    Read the article

  • Save and restore multiple layers within a Photoshop action that flattens

    - by SuitCase
    I'm editing comic pages with layers - "background", "foreground", "lineart" and "over lineart". I have a Photoshop action that includes a Mode-Bitmap command, which requires the image to be flattened. I need this part of the action because I use the Halftone Screen method of reducing the greyscale image to bitmap on the "background" layer, creating a certain effect. I am pretty sure there is no filter or anything else that gives the same effect. After the mode is changed to bitmap, my action changes things back to greyscale for further changes. This poses a problem. I only want to do the bitmap mode change on the background layer, and after I do the change I want to restore the layer structure as it was - with the foreground, lineart and over lineart layers back above the now-halftoned background. My current method of saving these layers and restoring them is clumsy. My action is able to automatically save the "foreground" layer by selecting it, cutting it, then pasting it back in after the mode changing is over. But, for the "ink" and "over ink" layers, I have to manually cut these layers, paste them into a new document, and later re-cut and re-paste after running my action. This is so clunky! What I would like to know is if it's possible to set aside my layers in an automated way, and then bring them back in, also in an automated way. An ugly (but functional) solution would be to replicate my actions of creating new documents and pasting them temporarily there, but I don't think Photoshop allows you to do things outside of your current document with an action. It seems to me that the only way to do what I want is to use the "hack" of incorporating the clipboard into the action as a clever hack, but that leaves me stuck as I have two more layers that can't fit onto that same clipboard. Help or suggestions would be appreciated. I can keep on doing it manually, but to have a comprehensive action would save me a ton of time.

    Read the article

  • java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap

    - by kongkea
    I've got this Error When I click listview to show full image size. how can i solve it? Error 11-20 10:27:47.039: D/AndroidRuntime(5078): Shutting down VM 11-20 10:27:47.039: W/dalvikvm(5078): threadid=1: thread exiting with uncaught exception (group=0x40c061f8) 11-20 10:27:47.047: E/AndroidRuntime(5078): FATAL EXCEPTION: main 11-20 10:27:47.047: E/AndroidRuntime(5078): java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap 11-20 10:27:47.047: E/AndroidRuntime(5078): at com.example.mylistview.MainActivity$1.onItemClick(MainActivity.java:103) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.widget.AdapterView.performItemClick(AdapterView.java:292) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.widget.AbsListView.performItemClick(AbsListView.java:1173) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2701) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.widget.AbsListView$1.run(AbsListView.java:3453) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.os.Handler.handleCallback(Handler.java:605) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.os.Handler.dispatchMessage(Handler.java:92) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.os.Looper.loop(Looper.java:137) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.app.ActivityThread.main(ActivityThread.java:4514) 11-20 10:27:47.047: E/AndroidRuntime(5078): at java.lang.reflect.Method.invokeNative(Native Method) 11-20 10:27:47.047: E/AndroidRuntime(5078): at java.lang.reflect.Method.invoke(Method.java:511) 11-20 10:27:47.047: E/AndroidRuntime(5078): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) 11-20 10:27:47.047: E/AndroidRuntime(5078): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) 11-20 10:27:47.047: E/AndroidRuntime(5078): at dalvik.system.NativeStart.main(Native Method) MainActivity public class MainActivity extends Activity { public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0; private ProgressDialog mProgressDialog; ArrayList<HashMap<String, Object>> MyArrList; @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Permission StrictMode if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } // Download JSON File new DownloadJSONFileAsync().execute(); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DOWNLOAD_JSON_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("Downloading....."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setCancelable(true); mProgressDialog.show(); return mProgressDialog; default: return null; } } // Show All Content public void ShowAllContent() { // listView1 final ListView lstView1 = (ListView)findViewById(R.id.listView1); lstView1.setAdapter(new ImageAdapter(MainActivity.this,MyArrList)); lstView1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { HashMap<String, Object> hm = (HashMap<String, Object>) lstView1.getAdapter().getItem(position); String imagePath = (String) hm.get("photo"); Intent i = new Intent(MainActivity.this,FullImageActivity.class); i.putExtra("fullImage", imagePath); startActivity(i); } }); } public class ImageAdapter extends BaseAdapter { private Context context; private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>(); public ImageAdapter(Context c, ArrayList<HashMap<String, Object>> myArrList) { // TODO Auto-generated method stub context = c; MyArr = myArrList; } public int getCount() { // TODO Auto-generated method stub return MyArr.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return position; } public long getItemId(int position) { // TODO Auto-generated method stub return position; } public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = inflater.inflate(R.layout.activity_column, null); } // ColImage ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath); imageView.getLayoutParams().height = 80; imageView.getLayoutParams().width = 80; imageView.setPadding(5, 5, 5, 5); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); try { imageView.setImageBitmap((Bitmap)MyArr.get(position).get("ImageThumBitmap")); } catch (Exception e) { // When Error imageView.setImageResource(android.R.drawable.ic_menu_report_image); } // ColImgID TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImgID); txtImgID.setPadding(10, 0, 0, 0); txtImgID.setText("ID : " + MyArr.get(position).get("id").toString()); // ColImgName TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgName); txtPicName.setPadding(50, 0, 0, 0); txtPicName.setText("Name : " + MyArr.get(position).get("first_name").toString()); return convertView; } } // Download JSON in Background public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> { protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS); } @Override protected Void doInBackground(String... params) { // TODO Auto-generated method stub String url = "http://192.168.10.104/adchara1/"; JSONArray data; try { data = new JSONArray(getJSONUrl(url)); MyArrList = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map; for(int i = 0; i < data.length(); i++){ JSONObject c = data.getJSONObject(i); map = new HashMap<String, Object>(); map.put("id", (String)c.getString("id")); map.put("first_name", (String)c.getString("first_name")); // Thumbnail Get ImageBitmap To Object map.put("photo", (String)c.getString("photo")); map.put("ImageThumBitmap", (Bitmap)loadBitmap(c.getString("photo"))); // Full (for View Popup) map.put("frame", (String)c.getString("frame")); MyArrList.add(map); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } protected void onPostExecute(Void unused) { ShowAllContent(); // When Finish Show Content dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS); removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS); } } /*** Get JSON Code from URL ***/ public String getJSONUrl(String url) { StringBuilder str = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { // Download OK HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { str.append(line); } } else { Log.e("Log", "Failed to download file.."); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return str.toString(); } /***** Get Image Resource from URL (Start) *****/ private static final String TAG = "Image"; private static final int IO_BUFFER_SIZE = 4 * 1024; public static Bitmap loadBitmap(String url) { Bitmap bitmap = null; InputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); copy(in, out); out.flush(); final byte[] data = dataStream.toByteArray(); BitmapFactory.Options options = new BitmapFactory.Options(); //options.inSampleSize = 1; bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options); } catch (IOException e) { Log.e(TAG, "Could not load Bitmap from: " + url); } finally { closeStream(in); closeStream(out); } return bitmap; } private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { android.util.Log.e(TAG, "Could not close stream", e); } } } private static void copy(InputStream in, OutputStream out) throws IOException { byte[] b = new byte[IO_BUFFER_SIZE]; int read; while ((read = in.read(b)) != -1) { out.write(b, 0, read); } } /***** Get Image Resource from URL (End) *****/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } FullImageActivity String imagePath = getIntent().getStringExtra("fullImage"); if(imagePath != null && !imagePath.isEmpty()){ File imageFile = new File(imagePath); if(imageFile.exists()){ Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath()); ImageView iv = (ImageView) findViewById(R.id.fullimage); iv.setImageBitmap(myBitmap); } }

    Read the article

  • png image store in database and retrieve in android 1.5

    - by hany
    hai, I am new to android. I have problem. This is my code but it will not work, the problem is in view binder. Please correct it. // this is my activity package com.android.Fruits2; import java.util.ArrayList; import java.util.HashMap; import android.app.ListActivity; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import android.widget.SimpleAdapter.ViewBinder; public class Fruits2 extends ListActivity { private DBhelper mDB; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.main); mDB = new DBhelper(this); mDB.Reset(); Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.icon); mDB.createPersonEntry(new PersonData(img, "Harsha", 24,"mca")); String[] columns = {mDB.KEY_ID, mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_AGE, mDB.KEY_STUDY}; String table = mDB.PERSON_TABLE; Cursor c = mDB.getHandle().query(table, columns, null, null, null, null, null); startManagingCursor(c); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.data, c, new String[] {mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_AGE, mDB.KEY_STUDY}, new int[] {R.id.img, R.id.name, R.id.age,R.id.study}); adapter.setViewBinder( new MyViewBinder()); setListAdapter(adapter); } } //my viewbinder package com.android.Fruits2; import android.database.Cursor; import android.graphics.BitmapFactory; import android.view.View; import android.widget.ImageView; import android.widget.SimpleCursorAdapter; public class MyViewBinder implements SimpleCursorAdapter.ViewBinder { public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if( (view instanceof ImageView) ) { ImageView iv = (ImageView) view; byte[] img = cursor.getBlob(columnIndex); iv.setImageBitmap(BitmapFactory.decodeByteArray(img, 0, img.length)); return true; } return false; } } // data package com.android.Fruits2; import android.graphics.Bitmap; public class PersonData { private Bitmap bmp; private String name; private int age; private String study; public PersonData(Bitmap b, String n, int k, String v) { bmp = b; name = n; age = k; study = v; } public Bitmap getBitmap() { return bmp; } public String getName() { return name; } public int getAge() { return age; } public String getStudy() { return study; } } //dbhelper package com.android.Fruits2; import java.io.ByteArrayOutputStream; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Bitmap; import android.provider.BaseColumns; public class DBhelper { public static final String KEY_ID = BaseColumns._ID; public static final String KEY_NAME = "name"; public static final String KEY_AGE = "age"; public static final String KEY_STUDY = "study"; public static final String KEY_IMG = "image"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private static final String DATABASE_NAME = "PersonalDB"; private static final int DATABASE_VERSION = 1; public static final String PERSON_TABLE = "Person"; private static final String CREATE_PERSON_TABLE = "create table "+PERSON_TABLE+" (" +KEY_ID+" integer primary key autoincrement, " +KEY_IMG+" blob not null, " +KEY_NAME+" text not null , " +KEY_AGE+" integer not null, " +KEY_STUDY+" text not null);"; private final Context mCtx; private boolean opened = false; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_PERSON_TABLE); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+PERSON_TABLE); onCreate(db); } } public void Reset() { openDB(); mDbHelper.onUpgrade(this.mDb, 1, 1); closeDB(); } public DBhelper(Context ctx) { mCtx = ctx; mDbHelper = new DatabaseHelper(mCtx); } private SQLiteDatabase openDB() { if(!opened) mDb = mDbHelper.getWritableDatabase(); opened = true; return mDb; } public SQLiteDatabase getHandle() { return openDB(); } private void closeDB() { if(opened) mDbHelper.close(); opened = false; } public void createPersonEntry(PersonData about) { openDB(); ByteArrayOutputStream out = new ByteArrayOutputStream(); about.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out); ContentValues cv = new ContentValues(); cv.put(KEY_IMG, out.toByteArray()); cv.put(KEY_NAME, about.getName()); cv.put(KEY_AGE, about.getAge()); cv.put(KEY_STUDY, about.getStudy()); mDb.insert(PERSON_TABLE, null, cv); closeDB(); } } //data.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageView android:id = "@+id/img" android:layout_width = "wrap_content" android:layout_height = "wrap_content" > </ImageView> <TextView android:id = "@+id/name" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textSize="15dp" android:textColor="#ff0000" > </TextView> <TextView android:id = "@+id/age" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textSize="15dp" android:textColor="#ff0000" /> <TextView android:id = "@+id/study" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textSize="15dp" android:textColor="#ff0000" /> </LinearLayout> When I run this in android 1.6 and 2.1, it works. But when I run in android 1.5, not work. My application is android 1.5. Please correct and send code to me. Thank you.

    Read the article

  • [OpenGL ES - Android] Better way to generate tiles

    - by Inoe
    Hi ! I'll start by saying that i'm REALLY new to OpenGL ES (I started yesterday =), but I do have some Java and other languages experience. I've looked a lot of tutorials, of course Nehe's ones and my work is mainly based on that. As a test, I started creating a "tile generator" in order to create a small Zelda-like game (just moving a dude in a textured square would be awsome :p). So far, I have achieved a working tile generator, I define a char map[][] array to store wich tile is on : private char[][] map = { {0, 0, 20, 11, 11, 11, 11, 4, 0, 0}, {0, 20, 16, 12, 12, 12, 12, 7, 4, 0}, {20, 16, 17, 13, 13, 13, 13, 9, 7, 4}, {21, 24, 18, 14, 14, 14, 14, 8, 5, 1}, {21, 22, 25, 15, 15, 15, 15, 6, 2, 1}, {21, 22, 23, 0, 0, 0, 0, 3, 2, 1}, {21, 22, 23, 0, 0, 0, 0, 3, 2, 1}, {26, 0, 0, 0, 0, 0, 0, 3, 2, 1}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1} }; It's working but I'm no happy with it, I'm sure there is a beter way to do those things : 1) Loading Textures : I create an ugly looking array containing the tiles I want to use on that map : private int[] textures = { R.drawable.herbe, //0 R.drawable.murdroite_haut, //1 R.drawable.murdroite_milieu, //2 R.drawable.murdroite_bas, //3 R.drawable.angledroitehaut_haut, //4 R.drawable.angledroitehaut_milieu, //5 }; (I cutted this on purpose, I currently load 27 tiles) All of theses are stored in the drawable folder, each one is a 16*16 tile. I then use this array to generate the textures and store them in a HashMap for a later use : int[] tmp_tex = new int[textures.length]; gl.glGenTextures(textures.length, tmp_tex, 0); texturesgen = tmp_tex; //Store the generated names in texturesgen for(int i=0; i < textures.length; i++) { //Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), textures[i]); InputStream is = context.getResources().openRawResource(textures[i]); Bitmap bitmap = null; try { //BitmapFactory is an Android graphics utility for images bitmap = BitmapFactory.decodeStream(is); } finally { //Always clear and close try { is.close(); is = null; } catch (IOException e) { } } // Get a new texture name // Load it up this.textureMap.put(new Integer(textures[i]),new Integer(i)); int tex = tmp_tex[i]; gl.glBindTexture(GL10.GL_TEXTURE_2D, tex); //Create Nearest Filtered Texture gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); //Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); //Use the Android GLUtils to specify a two-dimensional texture image from our bitmap GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } I'm quite sure there is a better way to handle that... I just was unable to figure it. If someone has an idea, i'm all ears. 2) Drawing the tiles What I did was create a single square and a single texture map : /** The initial vertex definition */ private float vertices[] = { -1.0f, -1.0f, 0.0f, //Bottom Left 1.0f, -1.0f, 0.0f, //Bottom Right -1.0f, 1.0f, 0.0f, //Top Left 1.0f, 1.0f, 0.0f //Top Right }; private float texture[] = { //Mapping coordinates for the vertices 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f }; Then, in my draw function, I loop through the map to define the texture to use (after pointing to and enabling the buffers) : for(int y = 0; y < Y; y++){ for(int x = 0; x < X; x++){ tile = map[y][x]; try { //Get the texture from the HashMap int textureid = ((Integer) this.textureMap.get(new Integer(textures[tile]))).intValue(); gl.glBindTexture(GL10.GL_TEXTURE_2D, this.texturesgen[textureid]); } catch(Exception e) { return; } //Draw the vertices as triangle strip gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3); gl.glTranslatef(2.0f, 0.0f, 0.0f); //A square takes 2x so I move +2x before drawing the next tile } gl.glTranslatef(-(float)(2*X), -2.0f, 0.0f); //Go back to the begining of the map X-wise and move 2y down before drawing the next line } This works great by I really think that on a 1000*1000 or more map, it will be lagging as hell (as a reminder, this is a typical Zelda world map : http://vgmaps.com/Atlas/SuperNES/LegendOfZelda-ALinkToThePast-LightWorld.png ). I've read things about Vertex Buffer Object and DisplayList but I couldn't find a good tutorial and nodoby seems to be OK on wich one is the best / has the better support (T1 and Nexus One are ages away). I think that's it, I've putted a lot of code but I think it helps. Thanks in advance !

    Read the article

  • BitBlt ignores CAPTUREBLT and seems to always capture a cached copy of the target...

    - by Jake Petroules
    I am trying to capture screenshots using the BitBlt function. However, every single time I capture a screenshot, the non-client area NEVER changes no matter what I do. It's as if it's getting some cached copy of it. The client area is captured correctly. If I close and then re-open the window, and take a screenshot, the non-client area will be captured as it is. Any subsequent captures after moving/resizing the window have no effect on the captured screenshot. Again, the client area will be correct. Furthermore, the CAPTUREBLT flag seems to do absolutely nothing at all. I notice no change with or without it. Here is my capture code: QPixmap WindowManagerUtils::grabWindow(WId windowId, GrabWindowFlags flags, int x, int y, int w, int h) { RECT r; switch (flags) { case WindowManagerUtils::GrabWindowRect: GetWindowRect(windowId, &r); break; case WindowManagerUtils::GrabClientRect: GetClientRect(windowId, &r); break; case WindowManagerUtils::GrabScreenWindow: GetWindowRect(windowId, &r); return QPixmap::grabWindow(QApplication::desktop()->winId(), r.left, r.top, r.right - r.left, r.bottom - r.top); case WindowManagerUtils::GrabScreenClient: GetClientRect(windowId, &r); return QPixmap::grabWindow(QApplication::desktop()->winId(), r.left, r.top, r.right - r.left, r.bottom - r.top); default: return QPixmap(); } if (w < 0) { w = r.right - r.left; } if (h < 0) { h = r.bottom - r.top; } #ifdef Q_WS_WINCE_WM if (qt_wince_is_pocket_pc()) { QWidget *widget = QWidget::find(winId); if (qobject_cast<QDesktopWidget*>(widget)) { RECT rect = {0,0,0,0}; AdjustWindowRectEx(&rect, WS_BORDER | WS_CAPTION, FALSE, 0); int magicNumber = qt_wince_is_high_dpi() ? 4 : 2; y += rect.top - magicNumber; } } #endif // Before we start creating objects, let's make CERTAIN of the following so we don't have a mess Q_ASSERT(flags == WindowManagerUtils::GrabWindowRect || flags == WindowManagerUtils::GrabClientRect); // Create and setup bitmap HDC display_dc = NULL; if (flags == WindowManagerUtils::GrabWindowRect) { display_dc = GetWindowDC(NULL); } else if (flags == WindowManagerUtils::GrabClientRect) { display_dc = GetDC(NULL); } HDC bitmap_dc = CreateCompatibleDC(display_dc); HBITMAP bitmap = CreateCompatibleBitmap(display_dc, w, h); HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap); // copy data HDC window_dc = NULL; if (flags == WindowManagerUtils::GrabWindowRect) { window_dc = GetWindowDC(windowId); } else if (flags == WindowManagerUtils::GrabClientRect) { window_dc = GetDC(windowId); } DWORD ropFlags = SRCCOPY; #ifndef Q_WS_WINCE ropFlags = ropFlags | CAPTUREBLT; #endif BitBlt(bitmap_dc, 0, 0, w, h, window_dc, x, y, ropFlags); // clean up all but bitmap ReleaseDC(windowId, window_dc); SelectObject(bitmap_dc, null_bitmap); DeleteDC(bitmap_dc); QPixmap pixmap = QPixmap::fromWinHBITMAP(bitmap); DeleteObject(bitmap); ReleaseDC(NULL, display_dc); return pixmap; } Most of this code comes from Qt's QWidget::grabWindow function, as I wanted to make some changes so it'd be more flexible. Qt's documentation states that: The grabWindow() function grabs pixels from the screen, not from the window, i.e. if there is another window partially or entirely over the one you grab, you get pixels from the overlying window, too. However, I experience the exact opposite... regardless of the CAPTUREBLT flag. I've tried everything I can think of... nothing works. Any ideas?

    Read the article

  • how to do android image animation

    - by user270811
    hi, i am trying to get a simple image animation going. i want to make it looks as if the helicopter's propeller blades are turning. i have 3 images for the helicopter, and i am showing one of these images depending on the animation progress. the problem is that all three images end up overlapping each other as opposed to just one image showing up at one time, thereby creating the animation. this is what i did so far, i even tried to clear canvas by doing this canvas.drawColor(Color.BLACK), but that would clear out the whole canvas, which is not what i want. this is what i have: 1) in the View class: static class Helicopter { private long mLastUpdate; private long mProgress = 0; private final float mX; private final float mY; private final Bitmap mHelicopter1; private final Bitmap mHelicopter2; private final Bitmap mHelicopter3; private final float mRadius; Helicopter(long mLastUpdate, float mX, float mY, Bitmap helicopter1, Bitmap helicopter2, Bitmap helicopter3) { this.mLastUpdate = mLastUpdate; this.mX = mX; this.mY = mY; this.mHelicopter1 = helicopter1; this.mHelicopter2 = helicopter2; this.mHelicopter3 = helicopter3; mRadius = ((float) mHelicopter1.getWidth()) / 2f; } public void update(long now) { mProgress += (now - mLastUpdate); if(mProgress >= 400L) { mProgress = 0; } mLastUpdate = now; } public void setNow(long now) { mLastUpdate = now; } public void draw(Canvas canvas, Paint paint) { if (mProgress < 150L) { canvas.drawBitmap(mHelicopter1, mX - mRadius, mY - mRadius, paint); } else if (mProgress < 300L) { canvas.drawBitmap(mHelicopter2, mX - mRadius, mY - mRadius, paint); } else if(mProgress < 400L) { canvas.drawBitmap(mHelicopter3, mX - mRadius, mY - mRadius, paint); } } public boolean done() { return mProgress > 700L; } } private ArrayList<Helicopter> mHelicopters = new ArrayList<Helicopter>(); 2) this is being called in the run() of a thread: private void doDraw(Canvas canvas) { final long now = SystemClock.elapsedRealtime(); canvas.save(); for (int i = 0; i < mHelicopters.size(); i++) { final Helicopter explosion = mHelicopters.get(i); explosion.update(now); } for (int i = 0; i < mHelicopters.size(); i++) { final Helicopter explosion = mHelicopters.get(i); explosion.draw(canvas, mPaint); } canvas.restore(); } can someone help me? i have looked at a lot of the examples on the web on animation, they seem to always involve text, but not images. thanks.

    Read the article

  • can't get texture to work

    - by user583713
    It been a while since I use android opengl but for what ever reason I get a white squre box and not the texture I what on the screen. Oh I do not think this would matter but just in case I put a linerlayout view first then the surfaceview on but anyway Here my code: public class GameEngine { private float vertices[]; private float textureUV[]; private int[] textureId = new int[1]; private FloatBuffer vertextBuffer; private FloatBuffer textureBuffer; private short indices[] = {0,1,2,2,1,3}; private ShortBuffer indexBuffer; private float x, y, z; private float rot, rotX, rotY, rotZ; public GameEngine() { } public void setEngine(float x, float y, float vertices[]){ this.x = x; this.y = y; this.vertices = vertices; ByteBuffer vbb = ByteBuffer.allocateDirect(this.vertices.length * 4); vbb.order(ByteOrder.nativeOrder()); vertextBuffer = vbb.asFloatBuffer(); vertextBuffer.put(this.vertices); vertextBuffer.position(0); vertextBuffer.clear(); ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2); ibb.order(ByteOrder.nativeOrder()); indexBuffer = ibb.asShortBuffer(); indexBuffer.put(indices); indexBuffer.position(0); indexBuffer.clear(); } public void draw(GL10 gl){ gl.glLoadIdentity(); gl.glTranslatef(x, y, z); gl.glRotatef(rot, rotX, rotY, rotZ); gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId[0]); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertextBuffer); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer); gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_SHORT, indexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } public void LoadTexture(float textureUV[], GL10 gl, InputStream is) throws IOException{ this.textureUV = textureUV; ByteBuffer tbb = ByteBuffer.allocateDirect(this.textureUV.length * 4); tbb.order(ByteOrder.nativeOrder()); textureBuffer = tbb.asFloatBuffer(); textureBuffer.put(this.textureUV); textureBuffer.position(0); textureBuffer.clear(); Bitmap bitmap = null; try{ bitmap = BitmapFactory.decodeStream(is); }finally{ try{ is.close(); is = null; gl.glGenTextures(1, textureId,0); gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); //Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); //Use the Android GLUtils to specify a two-dimensional texture image from our bitmap GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); //Clean up gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId[0]); bitmap.recycle(); }catch(IOException e){ } } } public void setVector(float x, float y, float z){ this.x = x; this.y = y; this.z = z; } public void setRot(float rot, float x, float y, float z){ this.rot = rot; this.rotX = x; this.rotY = y; this.rotZ = z; } public float getZ(){ return z; } }

    Read the article

  • Why some pictures are are crooked aftes using my function?

    - by Miko Kronn
    struct BitmapDataAccessor { private readonly byte[] data; private readonly int[] rowStarts; public readonly int Height; public readonly int Width; public BitmapDataAccessor(byte[] data, int width, int height) { this.data = data; this.Height = height; this.Width = width; rowStarts = new int[height]; for (int y = 0; y < Height; y++) rowStarts[y] = y * width; } public byte this[int x, int y, int color] // Maybe use an enum with Red = 0, Green = 1, and Blue = 2 members? { get { return data[(rowStarts[y] + x) * 3 + color]; } set { data[(rowStarts[y] + x) * 3 + color] = value; } } public byte[] Data { get { return data; } } } public static byte[, ,] Bitmap2Byte(Bitmap obraz) { int h = obraz.Height; int w = obraz.Width; byte[, ,] wynik = new byte[w, h, 3]; BitmapData bd = obraz.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); int bytes = Math.Abs(bd.Stride) * h; byte[] rgbValues = new byte[bytes]; IntPtr ptr = bd.Scan0; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); BitmapDataAccessor bda = new BitmapDataAccessor(rgbValues, w, h); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { wynik[j, i, 0] = bda[j, i, 2]; wynik[j, i, 1] = bda[j, i, 1]; wynik[j, i, 2] = bda[j, i, 0]; } } obraz.UnlockBits(bd); return wynik; } public static Bitmap Byte2Bitmap(byte[, ,] tablica) { if (tablica.GetLength(2) != 3) { throw new NieprawidlowyWymiarTablicyException(); } int w = tablica.GetLength(0); int h = tablica.GetLength(1); Bitmap obraz = new Bitmap(w, h, PixelFormat.Format24bppRgb); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { Color kol = Color.FromArgb(tablica[i, j, 0], tablica[i, j, 1], tablica[i, j, 2]); obraz.SetPixel(i, j, kol); } } return obraz; } Now, if I do: private void btnLoad_Click(object sender, EventArgs e) { if (dgOpenFile.ShowDialog() == DialogResult.OK) { try { Bitmap img = new Bitmap(dgOpenFile.FileName); byte[, ,] tab = Grafika.Bitmap2Byte(img); picture.Image = Grafika.Byte2Bitmap(tab); picture.Size = img.Size; } catch (Exception ex) { MessageBox.Show(ex.Message); } } } Most of pictures are handled correctly butsome not. Example of picture that doesn't work: It produce following result (this is only fragment of picture) : Why is that?

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >