How to reduce size of jpeg image in basic4android - basic4android

Hello at this time camera capturing image size is more than 1 mb. I want to reduce it to 20kb. Please help me.
Sub Camera1_PictureTaken (Data() As Byte)
camera1.StartPreview
DateTime.DateFormat ="HH.mm.ss.SS_dd-MM-yy_"
forDate=DateTime.Date(DateTime.now)
imei = pID.GetDeviceId
filename = forDate & imei& "_.jpeg"
File.MakeDir(File.DirRootExternal,"/data/data/a3a/cam/update/images")
out = File.OpenOutput(File.DirRootExternal,"/data/data/a3a/cam/update/images/"&filename, False)
out.WriteBytes(Data, 0, Data.Length)
out.Close
End Sub

Approach without library:
Sub UploadImage(Dir As String, Filename As String) As Byte()
Dim Image As Bitmap = LoadBitmapSample(Dir, Filename, 1920, 1080)
Dim Out As OutputStream
Out.InitializeToBytesArray(100)
Image.WriteToStream(Out, 90, "JPEG")
Return Out.ToBytesArray
End Sub

You can add RSImageProcessing library to your project.
This code will be bright your mind :)
Sub ReSize(b As Bitmap, newWidth As Int, newHeight As Int) As Bitmap
Dim r As RSImageProcessing
Return r.scaleBitmap(b, newWidth, newHeight)
End Sub

Related

Gmap.Net save image around selected marker

I have an application with GMap.Net showing various markers. I know how to take a screen shot of the current map and markers:
Dim sImageName As String = DateTime.Now.ToString(Format("yyyyMMdd-HHmmss")) & ".png"
Dim ThisMap As New Bitmap(Form2.myMap.Width, Form2.myMap.Height)
Form2.myMap.DrawToBitmap(ThisMap, New Rectangle(0, 0, Form2.myMap.Width, Form2.myMap.Height))
ThisMap.Save(sImagesFolder & sImageName)
What I would like to do is create an image for a selected marker. Instead of the image being the entire map shown on screen, it would center on the marker and show 100 pixels in each direction.
Does anyone know how to do that?
This is what I tried, but it gives me a blank image-- nothing shows up. I feel like this should be working...
Private Sub MyMap_OnMarkerClick(item As GMapMarker, e As Windows.Forms.MouseEventArgs) Handles myMap.OnMarkerClick
SelMarkerX = e.X
SelMarkerY = e.Y
Dim sImageName As String = DateTime.Now.ToString(Format("yyyyMMdd-HHmmss")) & ".png"
Dim ThisMap As New Bitmap(140,100)
myMap.DrawToBitmap(ThisMap, New Rectangle(SelMarkerX - 70, SelMarkerY - 50, 140, 100))
ThisMap.Save(sImagesFolder & sImageName)
End Sub
I just don't get it. If I write:
myMap.DrawToBitmap(ThisMap, New Rectangle(0, 0, 140, 100)
then I get what you might expect. I get the upper left corner of the existing map from 0 to 140 horizontally and 0 to 100 vertically. If I change it to this:
myMap.DrawToBitmap(ThisMap, New Rectangle(10, 0, 140, 100)
then I get 0 to 130 horizontally and not 10 to 140.
Well, I couldn't figure out how to do it with Gmap, so I wondered if I could crop it outside of Gmap and apparently that is common. Here is the code I used.
Dim ThisMap As New Bitmap(Form2.myMap.Width, Form2.myMap.Height)
Form2.myMap.DrawToBitmap(ThisMap, New Rectangle(0, 0, Form2.myMap.Width, Form2.myMap.Height))
ThisMap.Save(sImagesFolder & sImageName)
Dim LocX = SelMarkerX - 160 'x cord. of where crop starts
Dim LocY = SelMarkerY - 120 'y cord. of where crop starts
Dim CropW = 320 'Crop width
Dim CropH = 240 'Crop height
Dim CropRect As New Rectangle(LocX, LocY, CropW, CropH)
Dim OriginalImage = ThisMap
Dim CropImage = New Bitmap(CropRect.Width, CropRect.Height)
Using grp = Graphics.FromImage(CropImage)
grp.DrawImage(OriginalImage, New Rectangle(0, 0, CropRect.Width, CropRect.Height), CropRect, GraphicsUnit.Pixel)
CropImage.Save(sImagesFolder & sImageName)
End Using

Libre Office Macro to crop image

I have a Libre Office Macro and I need to crop an image, but I have been unable to find any helpful documentation or an example. Anyone have a tip how to do it?
dim noArgs()
dim emptyDocComponent as object
dim document as object
dim dispatcher as object
emptyDocComponent = StarDesktop.LoadComponentFromUrl("private:factory/swriter", "_blank", 0, noArgs())
frame = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
dim args1(3) as new com.sun.star.beans.PropertyValue
args1(0).Name = "FileName"
args1(0).Value = "file://" & inputPath
args1(1).Name = "FilterName"
args1(1).Value = "<All formats>"
args1(2).Name = "AsLink"
args1(2).Value = false
args1(3).Name = "Style"
args1(3).Value = "Graphics"
dispatcher.executeDispatch(frame, ".uno:InsertGraphic", "", 0, args1())
selection = ThisComponent.CurrentSelection
If selection.ImplementationName <> "SwXTextGraphicObject" Then
Exit Sub
End If
' this is what the macro recorder captured, but it was "rem" and non-functional
rem dispatcher.executeDispatch(document, ".uno:Crop", "", 0, Array())
*** edit
Here is what I am now using in case it helps someone else. I had a picture with a known size in pixels that needed to be cropped. Not entirely sure the calculation is completely accurate, but it is working so far.
dim noArgs()
dim emptyDocComponent as object
dim document as object
dim dispatcher as object
emptyDocComponent = StarDesktop.LoadComponentFromUrl("private:factory/swriter", "_blank", 0, noArgs())
frame = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
dim args1(3) as new com.sun.star.beans.PropertyValue
args1(0).Name = "FileName"
args1(0).Value = "file://" & inputPath
args1(1).Name = "FilterName"
args1(1).Value = "<All formats>"
args1(2).Name = "AsLink"
args1(2).Value = false
args1(3).Name = "Style"
args1(3).Value = "Graphics"
dispatcher.executeDispatch(frame, ".uno:InsertGraphic", "", 0, args1())
selection = ThisComponent.CurrentSelection
If selection.ImplementationName <> "SwXTextGraphicObject" Then
Exit Sub
End If
' size = (pixels / pixelsPerInch) * mm/in * scaling * actual graphic / displayed graphic
imageWidth = (int(pixelWidth) / int(xPixelsPerInch)) * 25.4 * 110 * (selection.actualSize.Width / selection.Width)
imageHeight = (int(pixelHeight) / int(yPixelsPerInch)) * 25.4 * 110 * (selection.actualSize.Height / selection.Height)
GraphicCrop = selection.GraphicCrop
GraphicCrop.Top = selection.actualSize.Height - imageHeight
GraphicCrop.Bottom = 0
GraphicCrop.Left = 0
GraphicCrop.Right = selection.actualSize.Width - imageWidth
selection.GraphicCrop = GraphicCrop
TextGraphicObject has a struct called GraphicCrop.
The following code was adapted from https://forum.openoffice.org/en/forum/viewtopic.php?f=25&t=72496.
selection = ThisComponent.CurrentSelection
If selection.ImplementationName <> "SwXTextGraphicObject" Then
Exit Sub
End If
pxPerInch = 100*25.6
cropFig = selection.GraphicCrop
cropFig.Left = 0.27*pxPerInch
cropFig.Right = 1.34*pxPerInch
cropFig.Top = 0.31*pxPerInch
cropFig.Bottom = 0.18*pxPerInch
selection.GraphicCrop = cropFig
Search the net for "DannyB" (in combination with OpenOffice) to find his very useful libraries on StarBasic macros for the Drawcomponent.
I'm pretty sure he has an example.
Other resource to look into: Andrew Pitonyak's "OpenOffice Macros Explained", might have an example as well.

How to convert int from an NSimage to JPEG in swift OS Xcode 7.3.1

I extra data from an image and save as int data. I want to convert back to an JPEG image. Thank You.
for j in 1 ..< dataCount!-1 {
var z = ImageArray![j]
if ( z > 0 ){
data[j] =z
}
else if (z < 0){
var y = 256 + z
data[j] = y
}
i += 1
}
*** need to convert int to byte ****** but don't know how to do that.
byteArray.writeToFile("/Users/picpath/picture.jpg", atomically: true )
to convert image into bytes you can use the following line of code.
var nsdata = UIImageJPEGRepresentation(data[j], 1)
The function takes two parameters , first parameter should be an image and the second parameter which is a float is used to define the compression ratio. by default we use "1"
This will convert image into bytes. Hopefully this will help you
Cheers

Responding to Manipulation delta - strange effect and overflow

In a test UWP form I have a basic manipulation test, code below. It draws 3 circles on a CanvasControl and sets up translation and scaling manipulation.
When I test this on a touch screen it basically does what I expect, translating and zooming the circles based on the position of 2 fingers on the screen. But if I pinch down beyond a certain point, the image starts to oscillate very quickly between 2 extents and will very quickly cause the code to stop with an overflow.
I put the canvas control in a grid and tried doing the manipulation on the canvas control from the grid control, and it does not suffer from the same problem although the effect of zooming and panning does not seem correct.
So it looks like the effect of my code as is, is an iteration, where a manipulation causing a render transform change could cause another manipulation, and it goes in circles until it settles - or if there is a problem of precision, perhaps due to the distance between the touch points getting too small, the iteration diverges until overflow.
Is this expected? What is the correct way to do this?
Private WithEvents Canv As New CanvasControl
Private WithEvents gr As New Grid
Private Sub Canv_Draw(sender As CanvasControl, args As CanvasDrawEventArgs) Handles Canv.Draw
args.DrawingSession.DrawCircle(50, 50, 25, Windows.UI.Colors.Blue)
args.DrawingSession.DrawCircle(250, 250, 25, Windows.UI.Colors.Blue)
args.DrawingSession.DrawCircle(500, 500, 25, Windows.UI.Colors.Blue)
End Sub
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Content = gr
gr.Children.Add(Canv)
Canv.ManipulationMode = ManipulationModes.Scale Or ManipulationModes.TranslateX Or ManipulationModes.TranslateY
end sub
Private Sub Canv_ManipulationDelta(sender As Object, e As ManipulationDeltaRoutedEventArgs) Handles Canv.ManipulationDelta
Dim t As New TranslateTransform
t.X = e.Cumulative.Translation.X
t.Y = e.Cumulative.Translation.Y
Dim s As New ScaleTransform
s.ScaleX = e.Cumulative.Scale
s.ScaleY = e.Cumulative.Scale
s.CenterX = e.Position.X
s.CenterY = e.Position.Y
Dim g As New TransformGroup
g.Children.Add(s)
g.Children.Add(t)
Canv.RenderTransform = g
End Sub
The common way in UWP is to use CompositeTransform, it supports Scale, Skew, Rotate and Translate.
Please see the BasicInput sample, especially the forth scenario
For the zooming issue, you can avoid it by using the following way:
Public NotInheritable Class MainPage
Inherits Page
Private WithEvents Canv As New CanvasControl
Private WithEvents gr As New Grid
Private Sub Canv_Draw(sender As CanvasControl, args As CanvasDrawEventArgs) Handles Canv.Draw
args.DrawingSession.DrawCircle(50, 50, 25, Windows.UI.Colors.Blue)
args.DrawingSession.DrawCircle(250, 250, 25, Windows.UI.Colors.Blue)
args.DrawingSession.DrawCircle(500, 500, 25, Windows.UI.Colors.Blue)
End Sub
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Content = gr
gr.Children.Add(Canv)
Canv.ManipulationMode = ManipulationModes.Scale Or ManipulationModes.TranslateX Or ManipulationModes.TranslateY
End Sub
Private Sub Canv_ManipulationDelta(sender As Object, e As ManipulationDeltaRoutedEventArgs) Handles Canv.ManipulationDelta
Dim tran = Transform(sender)
tran.ScaleX = tran.ScaleX * e.Delta.Scale
tran.ScaleY = tran.ScaleY * e.Delta.Scale
'System.Diagnostics.Debug.WriteLine("tran.ScaleX =" + tran.ScaleX.ToString() + " tran.ScaleY =" + tran.ScaleY.ToString())
End Sub
Private Function Transform(sender As Object) As CompositeTransform
Dim rect = TryCast(sender, CanvasControl)
rect.RenderTransformOrigin = New Point(0.5, 0.5)
Dim tran As New CompositeTransform
If TryCast(rect.RenderTransform, CompositeTransform) IsNot Nothing Then
tran = DirectCast(rect.RenderTransform, CompositeTransform)
Else
rect.RenderTransform = New CompositeTransform()
End If
Return tran
End Function
' utility method
Private Function Boundary(value As Double, min As Double, max As Double) As Double
If value > max Then
Return max
ElseIf value < min Then
Return min
Else
Return value
End If
End Function
End Class
Screenshot:
Some useful information in that, in the meantime I found a tidy solution, which was to leave the CanvasControl in the grid, and take the manipulation events from the grid and change the rendertransform of the Canvas control, that way there is no recursion. It also means that the natural translation is not correct - but this is easy to fix by multiplying it by the cumulative scale, ie. the full manipulation code becomes:
Private Sub GerberCanvGrid_ManipulationDelta(sender As Object, e As ManipulationDeltaRoutedEventArgs) Handles GerberCanvGrid.ManipulationDelta
Dim sf As New ScaleTransform
sf.ScaleX = e.Cumulative.Scale
sf.ScaleY = e.Cumulative.Scale
sf.CenterX = e.Position.X
sf.CenterY = e.Position.Y
Dim tt As New TranslateTransform
tt.X = e.Cumulative.Translation.X * e.Cumulative.Scale
tt.Y = e.Cumulative.Translation.Y * e.Cumulative.Scale
ManipulationTransform = New TransformGroup
ManipulationTransform.Children.Add(sf)
ManipulationTransform.Children.Add(tt)
GerberCanv.RenderTransform = ManipulationTransform
End Sub

how to determine the transparent color index of ICO image with PIL?

Specifically, this is from an .ico file, so there is no "transparent" "info" attribute like you would get in a gif. The below example illustrates converting Yahoo!'s favicon to a png using the correct transparency index of "0", which I guessed. how to detect that the ico is in fact transparent and that the transparency index is 0 ?
import urllib2
import Image
import StringIO
resp = urllib2.urlopen("http://www.yahoo.com/favicon.ico")
image = Image.open(StringIO.StringIO(resp.read()))
f = file("test.png", "w")
# I guessed that the transparent index is 0. how to
# determine it correctly ?
image.save(f, "PNG", quality=95, transparency=0)
looks like someone recognized that PIL doesn't really read ICO correctly (I can see the same thing after reconciling its source code with some research on the ICO format - there is an AND bitmap which determines transparency)
and came up with this extension:
http://www.djangosnippets.org/snippets/1287/
since this is useful for non-django applications, I've reposted here with a few tweaks to its exception throws:
import operator
import struct
from PIL import BmpImagePlugin, PngImagePlugin, Image
def load_icon(file, index=None):
'''
Load Windows ICO image.
See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format
description.
'''
if isinstance(file, basestring):
file = open(file, 'rb')
try:
header = struct.unpack('<3H', file.read(6))
except:
raise IOError('Not an ICO file')
# Check magic
if header[:2] != (0, 1):
raise IOError('Not an ICO file')
# Collect icon directories
directories = []
for i in xrange(header[2]):
directory = list(struct.unpack('<4B2H2I', file.read(16)))
for j in xrange(3):
if not directory[j]:
directory[j] = 256
directories.append(directory)
if index is None:
# Select best icon
directory = max(directories, key=operator.itemgetter(slice(0, 3)))
else:
directory = directories[index]
# Seek to the bitmap data
file.seek(directory[7])
prefix = file.read(16)
file.seek(-16, 1)
if PngImagePlugin._accept(prefix):
# Windows Vista icon with PNG inside
image = PngImagePlugin.PngImageFile(file)
else:
# Load XOR bitmap
image = BmpImagePlugin.DibImageFile(file)
if image.mode == 'RGBA':
# Windows XP 32-bit color depth icon without AND bitmap
pass
else:
# Patch up the bitmap height
image.size = image.size[0], image.size[1] >> 1
d, e, o, a = image.tile[0]
image.tile[0] = d, (0, 0) + image.size, o, a
# Calculate AND bitmap dimensions. See
# http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage
# for description
offset = o + a[1] * image.size[1]
stride = ((image.size[0] + 31) >> 5) << 2
size = stride * image.size[1]
# Load AND bitmap
file.seek(offset)
string = file.read(size)
mask = Image.fromstring('1', image.size, string, 'raw',
('1;I', stride, -1))
image = image.convert('RGBA')
image.putalpha(mask)
return image