Storing a BLOB in MySQL Database - mysql

I have an image uploaded to a server with location like : opt/glassfish/domains/domain1/applications/j2ee-modules/SmartbadgePortal/images/2badge.jpg
I am trying to read the contents of the image rather than the image information. I searched a lot and could get the following solution for it :
File uploadedFile = new File(path);
System.out.println("Uploaded File is *** : " + uploadedFile);
item.write(uploadedFile);
Image image = null;
image = ImageIO.read(uploadedFile);
System.out.println("Image Contents is *** : " + image);
However, the when I used System.out to print "image". I get :
Image Contents is * : BufferedImage#10d7a81: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace#722270 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 418 height = 387 #numDataElements 3 dataOff[0] = 2|#]
But , this is not what I need. I need the contents of the image and need to store it in a BLOB column in MySQL. Please help as I am been trying various methods like ByteArrayInputStream ,but every time I see only this info rather than image itself.

Although it's not the answer you're looking for, my recommendation is to store the image in your server's file system and saving the file name (and maybe directory) in your DB. Storing an image in a BLOB cell is usually not a good idea unless there's a specific reason.

Related

File corruption when inserting images to an existing word file

The following code applied to an existing file works for 2 images but beyond the file is marked as corrupted (though it can be recovered perfectly in word):
import docx
docTemplate = "TestTemplate.docx"
# docx job: add test subsections + images
doc_docx = docx.Document(docTemplate)
#doc_docx = docx.Document()
p = doc_docx.add_paragraph()
wp = p.add_run()
wp.add_picture('image.png')
wp.add_break()
wp.add_picture('image.png')
wp.add_break()
wp.add_picture('image.png')
doc_docx.save('TestFile2.docx')
The content of doc_docx.part.blob is available on pastebin
It appears that the docTemplate document was already containing some objects. Thanks to the answer from #Tores76 on python-docx github I could solve the "file corruption" issue. This means it was likely due to a duplicate docPr id
# fix id
doc_element = doc_docx._part._element
docPrs = doc_element.findall('.//' + qn('wp:docPr'))
for docPr in docPrs:
docPr.set('id',str(int(docPr.get('id'))+100000))

C# - Can not access File which is already being used - Iron OCR

I am using "Iron OCR", something like "Tesseract" to detect and scan certain Text from Screenshots.
Now I have the following error. Every time Iron OCR is used to scan an image for text it tries to access the Iron OCR log file which is somehow still used by the process before. So every time I get the error message that it can't access the log file because it is already in use. Nevertheless the Scan still works and I get a valid result even tho it gives me an exception because of that error.
My program works like this:
it takes a screenshots of certain areas of my screen.
it analyzes that image with Iron OCR and looks for text.
this process repeats itself infinitely.
I have following code:
//------------------------- # Capture Screenshot of specific Area # -------------------------\\
Rectangle bounds3;
Rect rect3 = new Rect();
bounds3 = new Rectangle(rect3.Left + 198, rect3.Top + 36, rect3.Right + 75 - rect3.Left - 10, rect3.Bottom + 30 - rect3.Top - 10);
CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top);
Bitmap result3 = new Bitmap(40, 14);
using (Graphics g = Graphics.FromImage(result3))
{
g.CopyFromScreen(new Point(bounds3.Left, bounds3.Top), Point.Empty, bounds3.Size);
}
//------------------------- # Analyze Image for Text # -------------------------\\
var Ocr = new IronTesseract();
using (var Input = new OcrInput(result))
{
Input.Contrast();
Input.EnhanceResolution(300);
Input.Invert();
Input.Sharpen();
Input.ToGrayScale();
try
{
//------------------- # This causes the Error - Using Try Catch to Ignore it # -------------------\\
var Result = Ocr.Read(Input);
text = Result.Text;
}
catch
{
}
}
Also removing all the above only using their "1 Line Code" gives the same error message:
var Result = new IronTesseract().Read(#"images\image.png").Text;
I hope someone can help me to figure out what exactly causes that issue.

How do I append text to the start, middle, and end of each line from one file to another using python3?

I am writing a script to change the formatting of the text from one file, and create a new text file with the changes in formatting.
I have been able to remove unwanted characters, but haven't found a way to append text to the beginning of every line in the file.
Content from the original file looks like:
DMA 123 USA 12345
What I need it to look like after appending data to the start, middle, and end of the string:
<option label="DMA 123 USA" value="123"></option>
I have almost 100 lines that vary some, but follow the above formatting. I am trying to automate this as it will be a frequent task to adjust the original file to the new format for web publishing
I have been searching and haven't found any way to do it yet. Here is my current code:
path = 'file.txt'
tvfile = open(path,'r')
days = tvfile.read()
new_path = 'tvs.txt'
new_days = open(new_path,'w')
replace_me = ['-' ,'(' ,')' ,',' , '"' , ]
for item in replace_me:
days = days.replace(item,'')
days = days.strip()
new_days.write(days)
print(days)
tvfile.close()
new_days.close()
Nit: you need to prepend, not append. That said, try something along these lines:
buffer = ""
for item in replace_me:
line = "<option label=\""
line = line + days.replace(item,'').strip()
line = line + "\"></option>"
buffer = buffer + line
new_days.write(buffer)

How to change the name of images when user save them?

How can I change the name of images to website URL when user save them (save image as) , like this site :
Simple Desktop Website
for example the name of the image is : man.png
but when user save that the name of image will change to mysite.com.png
This is just for your understanding
string _strName = "mysite.com.png";
System.Web.HttpResponse _response = System.Web.HttpContext.Current.Response;
_response.ClearContent();
_response.Clear();
_response.ContentType = "text/plain";
_response.AddHeader("Content-Disposition", "attachment; filename=" + _strName + ";");
_response.TransmitFile(Server.MapPath("Img\\zentree_1.png")); //location of your Image file
_response.Flush();
_response.End();
If that is not your expectation, then do reply with your code,
I believe i can help you on this.

How to get the size (in pixels) of a jpeg image I get with UrlFetchApp.fetch(photoLink)?

In a script that sends email in HTML format I add an image that is stored in a public shared folder.
I get the blob using UrlFetchApp.fetch(photoLink) but the image has not necessarily the right size so in the html code I use width and height attributes (for now with fixed values, see code below) but I'd like it to be automatically resized with the right ratio.
To achieve that I need to know how to get the original size of the image (height and width) but I just don't know how to get it without inserting the image in an intermediate document (which would work but I find this approach a bit weird and unnecessarily complicated... moreover I don't feel like having a useless doc appearing each time I change the image file).
Here is the relevant part of the code that creates the email message :
function sendMail(test,rowData,genTitle,day,title,stHour,endHour){
var photoLink = sh.getRange('H1').getValue();
var image = UrlFetchApp.fetch(photoLink);
//************* find the pixel size of the image to get its ratio
var msgTemplate = '<IMG SRC="'+photoLink+'" BORDER=0 ALT="logo" HEIGHT=200 WIDTH=300><BR><BR>'+
'Résumé de vos réservations au nom de <NOM><BR><BR><BR><table style="background-color:lightblue;border-collapse:collapse;" border = 1 cellpadding = 5><th></th><th><TABLEHEADER></th><EVENTS></table><BR><CONCLUSION><BR>Cordialement,<BR><BR>';
var mailTitle = 'Confirmation de réservation - '+getTextFromHtml(genTitle);
var descr = '';
for(var d = 0;d<day.length;++d){
Logger.log(Number(rowData[(d+5)]));
var content = '<tr bgcolor="#ffffbb" width="100%"><td><NUMBER> </td><td > <DESCRIPTION></td></tr>'
if(Number(rowData[(d+5)])>1){var pl = ' places'}else{var pl = ' place'};
content = content.replace('<NUMBER>',rowData[(d+5)]+pl);
content = content.replace('<DESCRIPTION>',title[d]+' de '+stHour[d]+' heures à '+endHour[d]+' heures');
if(Number(rowData[(d+5)])>0){
descr += content;
}
}
msgTemplate = msgTemplate.replace('<NOM>',rowData[1]).replace('<EVENTS>',descr).replace('<TABLEHEADER>',genTitle);
var textVersion = getTextFromHtml(msgTemplate.replace(/<br>/gi,'\n').replace(/<td>/gi,'\n'));
// Logger.log(textVersion)
if(test){
MailApp.sendEmail(Session.getEffectiveUser().getEmail(),mailTitle, textVersion,{'htmlBody':msgTemplate,"replyTo" : retour});
}
else
{
MailApp.sendEmail(rowData[2],mailTitle, textVersion,{'htmlBody':msgTemplate,"replyTo" : retour});
}
}
There is no easy way within Apps Script to figure out what an image size would be. There are some other projects that might be able to analyze the bitmap data and give you dimensions.
The last time I had to solve this problem. I just wrote a simple App Engine app to do the image math for me -
import webapp2
from google.appengine.api import urlfetch
from google.appengine.api import images
from django.utils import simplejson
class MainHandler(webapp2.RequestHandler):
def get(self):
url = self.request.get('url')
imgResp = urlfetch.fetch(url) #eg. querystring - url=http://xyz.com/img.jpg
if imgResp.status_code == 200:
img = images.Image(imgResp.content);
jsonResp = {"url":url, "h":img.height, "w":img.width, "format":img.format}
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(simplejson.dumps(jsonResp))
app = webapp2.WSGIApplication([('/imageinfo', MainHandler)], debug=True)
And then I call it from Apps Script like this -
function checkImageSizes() {
var imageUrls = ['http://developers.google.com/apps-script/images/carousel0.png','http://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg420exif.jpg'];
for(var i in imageUrls){
var resp = JSON.parse(UrlFetchApp.fetch('http://arunimageinfo.appspot.com/imageinfo?url='+imageUrls[i]).getContentText());
Logger.log('Image at %s is %s x %s',resp.url,resp.w,resp.h);
}
}
You are welcome to use my App Engine instance if your volume is a couple of times a week :)
I doubt you can do this in apps script. Certainly not natively but you might be able to find or adapt a jpg library that looks at the binary blob header and extracts the image size.